import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ClassVersionChecker { public static void main(String[] args) throws IOException { System.out.println(System.getProperty("java.version")); String canonicalName = ClassVersionChecker.class.getCanonicalName(); String classPathSeparate = "/"; String extension = ".class"; String path = ClassVersionChecker.class.getResource(classPathSeparate + canonicalName.replace(".", classPathSeparate) + extension).getPath(); File file = new File(path); checkClassVersion(file); } private static void checkClassVersion(File classFile) throws IOException { DataInputStream in = new DataInputStream (new FileInputStream(classFile)); int magic = in.readInt(); if (magic != 0xcafebabe) { System.out.println(classFile.getName() + " is not a valid class!"); } int minor = in.readUnsignedShort(); int major = in.readUnsignedShort(); System.out.println(classFile.getName() + ": " + major + " . " + minor); in.close(); } }
JDK1.8: 1.8.0_65 ClassVersionChecker.class: 52 . 0
JDK1.6: 1.6.0_45 ClassVersionChecker.class: 50 . 0
时间: 2024-10-03 23:18:18