当改变了jdk版本时,在编译java时,会遇到Unsupported major.minor version错误。
错误信息如下 :
Unsupported major.minor version 50.0
Unsupported major.minor version 49.0 (我在jdk1.4 和1.5切换时就遇到了这个错误)
Unsupported major.minor version 48.0
二、错误原因:
类似错误均属于Java版本问题,即JDK版本过低,只要选择相对应的JDK版本编译即可。
48,49,50是Java编译器内部的版本号:
Unsupported major.minor version 50.0 对应于 JDK1.6(JRE1.6)
Unsupported major.minor version 49.0 对应于 JDK1.5(JRE1.5)
Unsupported major.minor version 48.0 对应于 JDK1.4(JRE1.4)
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
如果可以拿到源代码,用当前环境JDK重新编译,再运行即可。(记得使用 -target -source 参数)
如果拿不到源代码,就要确认classes的编译器本版,然后用该版本运行。
下面是JDK 1.1 到 JDK 1.7 编译器编译出的 class 的默认 minor.major version
JDK 编译器版本 | target 参数 | 十六进制 minor.major | 十进制 minor.major |
jdk1.1.8 | 不能带 target 参数 | 00 03 00 2D | 45.3 |
jdk1.2.2 | 不带(默认为 -target 1.1) | 00 03 00 2D | 45.3 |
jdk1.2.2 | -target 1.2 | 00 00 00 2E | 46.0 |
jdk1.3.1_19 | 不带(默认为 -target 1.1) | 00 03 00 2D | 45.3 |
jdk1.3.1_19 | -target 1.3 | 00 00 00 2F | 47.0 |
j2sdk1.4.2_10 | 不带(默认为 -target 1.2) | 00 00 00 2E | 46.0 |
j2sdk1.4.2_10 | -target 1.4 | 00 00 00 30 | 48.0 |
jdk1.5.0_11 | 不带(默认为 -target 1.5) | 00 00 00 31 | 49.0 |
jdk1.5.0_11 | -target 1.4 -source 1.4 | 00 00 00 30 | 48.0 |
jdk1.6.0_01 | 不带(默认为 -target 1.6) | 00 00 00 32 | 50.0 |
jdk1.6.0_01 | -target 1.5 | 00 00 00 31 | 49.0 |
jdk1.6.0_01 | -target 1.4 -source 1.4 | 00 00 00 30 | 48.0 |
jdk1.7.0 | 不带(默认为 -target 1.6) | 00 00 00 32 | 50.0 |
jdk1.7.0 | -target 1.7 | 00 00 00 33 | 51.0 |
jdk1.7.0 | -target 1.4 -source 1.4 | 00 00 00 30 | 48.0 |
Apache Harmony 5.0M3 | 不带(默认为 -target 1.2) | 00 00 00 2E | 46.0 |
Apache Harmony 5.0M3 | -target 1.4 | 00 00 00 30 | 48.0 |
时间: 2024-10-31 02:27:55