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

前端 未结 8 956
星月不相逢
星月不相逢 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:01

    This gets you the contents of the class file:

    MysteryClass.class.getResourceAsStream("MysteryClass.class")

    Then look at bytes 5-8 to get the minor and major version. A mapping between those numbers and the JDK releases can be found here.

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

    On Linux, you can use the file command on a class file, which I found easiest for my use case. For example:

    $ file Foo.class
    Foo.class: compiled Java class data, version 50.0 (Java 1.6)
    
    0 讨论(0)
  • 2020-11-28 08:08
    import java.io.*;
    
    public class ClassVersionChecker {
        public static void main(String[] args) throws IOException {
            for (int i = 0; i < args.length; i++)
                checkClassVersion(args[i]);
        }
    
        private static void checkClassVersion(String filename)
            throws IOException
        {
            DataInputStream in = new DataInputStream
                (new FileInputStream(filename));
    
            int magic = in.readInt();
            if(magic != 0xcafebabe) {
                System.out.println(filename + " is not a valid class!");;
            }
            int minor = in.readUnsignedShort();
            int major = in.readUnsignedShort();
            System.out.println(filename + ": " + major + " . " + minor);
            in.close();
        }
    }
    

    The possible values are :

    major  minor Java platform version 
    45       3           1.0
    45       3           1.1
    46       0           1.2
    47       0           1.3
    48       0           1.4
    49       0           5
    50       0           6
    51       0           7
    52       0           8
    53       0           9
    54       0           10
    55       0           11
    56       0           12
    57       0           13
    58       0           14
    
    0 讨论(0)
  • 2020-11-28 08:10

    As others have shown, it is easy enough to do by reading the first eight bytes of a class file. If you want a pre-built binary library, you can download one here.

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

    basszero's approach can be done via the UNIX command line, and the "od(1)" command:

    % od -x HelloWorldJava.class |head -2
    0000000 feca beba 0000 3100 dc00 0007 0102 2a00
    0000020 6f63 2f6d 6e65 6564 6163 642f 6d65 2f6f
    

    "feca beba" is the magic number. The "0000 3100" is 0x31, which represents J2SE 5.0.

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

    Apache BCEL provides this API:

    JavaClass c = Repository.lookupClass("com.x.MyClass")
    c.getMinor();
    c.getMajor();
    
    0 讨论(0)
提交回复
热议问题