Answers:
使用JDK随附的javap工具。该-verbose
选项将打印类文件的版本号。
> javap -verbose MyClass
Compiled from "MyClass.java"
public class MyClass
SourceFile: "MyClass.java"
minor version: 0
major version: 46
...
仅显示版本:
WINDOWS> javap -verbose MyClass | find "version"
LINUX > javap -verbose MyClass | grep version
无需第三方API即可轻松读取类文件签名并获取这些值。您需要做的就是读取前8个字节。
ClassFile {
u4 magic;
u2 minor_version;
u2 major_version;
对于51.0版的类文件(Java 7),起始字节为:
CA FE BA BE 00 00 00 33
...其中0xCAFEBABE是魔术字节,0x0000是次要版本,0x0033是主要版本。
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException {
ClassLoader loader = Demo.class.getClassLoader();
try (InputStream in = loader.getResourceAsStream("Demo.class");
DataInputStream data = new DataInputStream(in)) {
if (0xCAFEBABE != data.readInt()) {
throw new IOException("invalid header");
}
int minor = data.readUnsignedShort();
int major = data.readUnsignedShort();
System.out.println(major + "." + minor);
}
}
}
遍历目录(File)和档案(JarFile)寻找类文件是微不足道的。
Oracle的Joe Darcy的博客列出了从Java到Java 7 的类版本到JDK版本的映射:
Target Major.minor Hex
1.1 45.3 0x2D
1.2 46.0 0x2E
1.3 47.0 0x2F
1.4 48.0 0x30
5 (1.5) 49.0 0x31
6 (1.6) 50.0 0x32
7 (1.7) 51.0 0x33
8 (1.8) 52.0 0x34
9 53.0 0x35
在类Unix上
文件/path/to/Thing.class
还将提供文件类型和版本。输出如下所示:
编译的Java类数据,版本49.0
也许这对某人也有帮助。看起来有一种更简单的方法来获取用于编译/构建.class的JAVA版本。这种方式对于JAVA版本的应用程序/类自检很有用。
我遍历了JDK库,发现了这个有用的常量: com.sun.deploy.config.BuiltInProperties.CURRENT_VERSION。我不知道它何时在JAVA JDK中。
尝试这段代码的几个版本常量,我得到以下结果:
src:
System.out.println("JAVA DEV ver.: " + com.sun.deploy.config.BuiltInProperties.CURRENT_VERSION);
System.out.println("JAVA RUN v. X.Y: " + System.getProperty("java.specification.version") );
System.out.println("JAVA RUN v. W.X.Y.Z: " + com.sun.deploy.config.Config.getJavaVersion() ); //_javaVersionProperty
System.out.println("JAVA RUN full ver.: " + System.getProperty("java.runtime.version") + " (may return unknown)" );
System.out.println("JAVA RUN type: " + com.sun.deploy.config.Config.getJavaRuntimeNameProperty() );
输出:
JAVA DEV ver.: 1.8.0_77
JAVA RUN v. X.Y: 1.8
JAVA RUN v. W.X.Y.Z: 1.8.0_91
JAVA RUN full ver.: 1.8.0_91-b14 (may return unknown)
JAVA RUN type: Java(TM) SE Runtime Environment
在类字节码中确实存储了常量-请参见Main.call中红色标记的部分- 存储在.class字节码中的常量
常量在类中,用于检查JAVA版本是否已过期(请参阅Java如何检查已过期)。
一个基于Java的使用版本魔术数字的解决方案。程序本身使用它下面的内容来检测其字节码版本。
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
public class Main {
public static void main(String[] args) throws DecoderException, IOException {
Class clazz = Main.class;
Map<String,String> versionMapping = new HashMap();
versionMapping.put("002D","1.1");
versionMapping.put("002E","1.2");
versionMapping.put("002F","1.3");
versionMapping.put("0030","1.4");
versionMapping.put("0031","5.0");
versionMapping.put("0032","6.0");
versionMapping.put("0033","7");
versionMapping.put("0034","8");
versionMapping.put("0035","9");
versionMapping.put("0036","10");
versionMapping.put("0037","11");
versionMapping.put("0038","12");
versionMapping.put("0039","13");
versionMapping.put("003A","14");
InputStream stream = clazz.getClassLoader()
.getResourceAsStream(clazz.getName().replace(".", "/") + ".class");
byte[] classBytes = IOUtils.toByteArray(stream);
String versionInHexString =
Hex.encodeHexString(new byte[]{classBytes[6],classBytes[7]});
System.out.println("bytecode version: "+versionMapping.get(versionInHexString));
}
}
此类Java类扫描目录列表下找到的所有WAR内容和JAR的内容,并打印每个组件的Java类文件版本的摘要,包括WAR中的每个JAR:
public class ShowClassVersions {
private static final byte[] CLASS_MAGIC = new byte[] {(byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe};
private final byte[] bytes = new byte[8];
private TreeMap<String,ArrayList<String>> vers = new TreeMap<>();
private void scan(Path f) throws IOException {
if (Files.isDirectory(f)) {
Pattern pattern = Pattern.compile("\\.[wj]ar$"); // or |\\.class
try(var stream = Files.find(f, Integer.MAX_VALUE, (p,a) -> a.isRegularFile() && pattern.matcher(p.toString()).find())) {
stream.forEach(this::scanFile);
}
return;
}
scanFile(f);
}
private void scanFile(Path f) {
String fn = f.getFileName().toString();
try {
if (fn.endsWith(".jar"))
scanArchive(f);
else if (fn.endsWith(".war"))
scanArchive(f);
else if (fn.endsWith(".class"))
record(f, versionOfClass(f));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void scanArchive(Path p) throws IOException {
try(InputStream in = Files.newInputStream(p)) {
scanArchive(p.toAbsolutePath().toString(), in);
}
}
private String scanArchive(String desc, InputStream in) throws IOException {
String version = null;
ZipInputStream zip = new ZipInputStream(in);
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
String name = entry.getName();
if (version == null && name.endsWith(".class")) {
version = versionOfClass(zip);
}
else if (name.endsWith(".jar")) {
scanArchive(desc+" ==>> "+name, zip);
}
}
if (version != null)
record(desc, version);
return version;
}
private String versionOfClass(Path p) throws IOException {
String version = null;
try(InputStream in = Files.newInputStream(p)) {
version = versionOfClass(in);
}
return version;
}
private String versionOfClass(InputStream in) throws IOException {
String version = null;
int c = in.read(bytes);
if (c == bytes.length && Arrays.mismatch(bytes, CLASS_MAGIC) == CLASS_MAGIC.length) {
int minorVersion = (bytes[4] << 8) + (bytes[4] << 0);
int majorVersion = (bytes[6] << 8) + (bytes[7] << 0);
version = ""+majorVersion + "." + minorVersion;
}
return version;
}
private void record(String p, String v) {
vers.computeIfAbsent(String.valueOf(v), k -> new ArrayList<String>()).add(p);
}
private void record(Path p, String v) {
record(p.toAbsolutePath().toString(), v);
}
public static void main(String[] args) throws IOException {
ShowClassVersions v = new ShowClassVersions();
var files = Arrays.stream(args).map(Path::of).collect(Collectors.toList());
for (var f : files) {
v.scan(f);
}
for (var ver : v.vers.keySet()) {
System.out.println("Version: "+ver);
for (var p : v.vers.get(ver)) {
System.out.println(" "+p);
}
};
}
}