使用java怎么获取字节码的编译版本?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
示例代码
package com.jinggujin.util;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.util.Enumeration;import java.util.jar.JarEntry;import java.util.jar.JarFile;public class JavaVersionUtils{ private static final int JAVA_CLASS_MAGIC = 0xCAFEBABE; public final static int JDK_1_2 = 46; public final static int JDK_1_3 = 47; public final static int JDK_1_4 = 48; public final static int JDK_5 = 49; public final static int JDK_6 = 50; public final static int JDK_7 = 51; public final static int JDK_8 = 52; public static int getJDKVersion() { String version = System.getProperty("java.version"); if (version != null && version.matches("1\\.\\d.*")) { int v = Integer.parseInt(version.charAt(2) + ""); if (v >= 2) { return 44 + v; } } return -1; } public static int getCompileVersion(File file) throws Exception { if (file == null || !file.isFile() || !file.getName().matches(".*\\.((jar)|(class))")) { throw new IllegalArgumentException("the file must be a jar or class."); } int version = -1; if (file.getName().endsWith("jar")) { JarFile jarFile = new JarFile(file); Enumeration<JarEntry> enumeration = jarFile.entries(); while (enumeration.hasMoreElements()) { JarEntry entry = enumeration.nextElement(); if (entry.getName().endsWith(".class")) { InputStream in = jarFile.getInputStream(entry); version = getVersion(in); in.close(); break; } } jarFile.close(); } else { InputStream in = new FileInputStream(file); version = getVersion(in); in.close(); } return version; } private static int getVersion(InputStream in) throws Exception { DataInputStream dis = new DataInputStream(in); // ,前面8个字节CA FE BA BE 是固定的,之后4个字节是次版本号,次版本号后面的4个字节是jdk的版本号 int magic = dis.readInt(); if (magic == JAVA_CLASS_MAGIC) { // int minorVersion = dis.readUnsignedShort(); int majorVersion = dis.readUnsignedShort(); // Java 1.2 >> 46 // Java 1.3 >> 47 // Java 1.4 >> 48 // Java 5 >> 49 // Java 6 >> 50 // Java 7 >> 51 // Java 8 >> 52 return majorVersion; } return -1; }}
看完上述内容,你们掌握使用java怎么获取字节码的编译版本的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网行业资讯频道,感谢各位的阅读!