Java API找出JDK版本的类文件是为其编译的? [英] Java API to find out the JDK version a class file is compiled for?

查看:99
本文介绍了Java API找出JDK版本的类文件是为其编译的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何Java API可以找到为其编译的类文件的JDK版本?当然有javap工具可以找到此处。但是我想以编程方式执行此操作,以便我可以警告用户为适当的JDK编译它

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. However I want to do it programmatically so that that I could warn the user to compile it for the appropriate 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

这篇关于Java API找出JDK版本的类文件是为其编译的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆