是否有任何Java API可以找出为类文件编译的JDK版本?当然,有javap工具可以找到here中提到的主要版本。但是我想以编程方式进行操作,以便可以警告用户针对适当的JDK进行编译

最佳答案

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();
    }
}

可能的值为:
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

关于version - Java API找出要为其编译类文件的JDK版本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1293308/

10-11 01:28