读取和显示Java .class版本的工具


115

你们中没有人知道将搜索.class文件然后显示其编译版本的工具吗?

我知道您可以在十六进制编辑器中单独查看它们,但是我要查看很多类文件(由于某种原因,我的大型应用程序中的某些内容正在编译为Java6)。


1
比较流行的重复stackoverflow.com/questions/1096148/…提供了一些此处未提及的便捷工具。
Vadzim 2014年

Answers:


142

使用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

2
版本major.minor = JDK / JavaSE; 45.3 = JDK1.1; 46.0 = JDK1.2; 47.0 = JDK1.3; 48.0 = JDK1.4; 49.0 = JavaSE5(1.5); 51.0 = JavaSE7(1.7); 50.0 = JavaSE6(1.6); 52.0 = JavaSE8(1.8); 53.0 = JavaSE9; 54.0 = JavaSE10; 55.0 = JavaSE11; 56.0 = JavaSE12; 57.0 = JavaSE13; 58.0 = JavaSE14;
nephewtom

45

无需第三方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

还要记住,只有在启动Java时启用assert才能运行assert,因此,如果您不使用IllegalArgumentException(例如),则可能会读取垃圾文件
jontejj

21

在类Unix上

文件/path/to/Thing.class

还将提供文件类型和版本。输出如下所示:

编译的Java类数据,版本49.0


(从WMR的答案简化)
phunehehe 2011年

这比其他解决方案更简单
mmuller

9

如果您使用的是Unix系统,则可以执行

find /target-folder -name \*.class | xargs file | grep "version 50\.0"

(对于Java6类,我的文件版本说“ Java 5类编译数据,版本50.0”)。


在macOS(至少为10.12.6)上,输出甚至更有用: file *.class 产生: ClassName.class: compiled Java class data, version 50.0 (Java 1.6)
Gary

5

另一个Java版本检查

od -t d -j 7 -N 1 ApplicationContextProvider.class | head -1 | awk '{print "Java", $2 - 44}'

5

在月食中,如果您没有附加源。注意附加源按钮后的第一行。

//从CDestinoLog.java(版本1.5:49.0,超级位)编译

在此处输入图片说明


2

也许这对某人也有帮助。看起来有一种更简单的方法来获取用于编译/构建.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如何检查已过期)。


1

一个基于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));
    }
}

0

此类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);
            }
        };
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.