Java API to find out the JDK version a class file is compiled for?

前端 未结 8 957
星月不相逢
星月不相逢 2020-11-28 07:52

Are there any Java APIs to find out the JDK version a class file is compiled for? Of course there is the javap tool to find out the major version as mentioned in here. Howev

相关标签:
8条回答
  • 2020-11-28 08:17

    JavaP does have an API, but it's specific to the Sun JDK.

    It's found in tools.jar, under sun/tools/javap/Main.class.

    0 讨论(0)
  • 2020-11-28 08:18

    Just read the class file directly. It's VERY easy to figure out the version. Check out the the spec and wiki and then try the code. Wrapping this code and making is more useful/pretty is left as an exercise. Alternatively, you could use a library like BCEL, ASM, or JavaAssist

    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    public class ClassVersionTest
    {
        private static final int JAVA_CLASS_MAGIC = 0xCAFEBABE;
    
        public static void main(String[] args)
        {
            try
            {
                DataInputStream dis = new DataInputStream(new FileInputStream("Test.class"));
                int magic = dis.readInt();
                if(magic == JAVA_CLASS_MAGIC)
                {
                    int minorVersion = dis.readUnsignedShort();
                    int majorVersion = dis.readUnsignedShort();
    
                    /**
                     * majorVersion is ...
                     * J2SE 6.0 = 50 (0x32 hex),
                     * J2SE 5.0 = 49 (0x31 hex),
                     * JDK 1.4 = 48 (0x30 hex),
                     * JDK 1.3 = 47 (0x2F hex),
                     * JDK 1.2 = 46 (0x2E hex),
                     * JDK 1.1 = 45 (0x2D hex).
                     */
    
                    System.out.println("ClassVersionTest.main() " + majorVersion + "." + minorVersion);
                }
                else
                {
                    // not a class file
                }
            }
            catch (FileNotFoundException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题