问题描述
字节码是否依赖于创建它的 Java 版本?
Does the bytecode depend on the version of Java it was created with?
推荐答案
如果我在最新的 JDK 中编译了 java 文件,那么旧的 JVM 是否能够运行 .class 文件?
If I compiled a java file in the newest JDK, would an older JVM be able to run the .class files?
这取决于三件事:
您正在谈论的实际 Java 版本.例如,1.4.0 JVM 可以运行由 1.4.2 编译器编译的代码,但 1.3.x JVM 不能1.
使用的编译标志.有一个 -target
编译器标志,告诉它生成将在较旧的(目标)JVM 上运行的代码.-source
编译器标志告诉它只接受旧版 JVM 的语言特性.(这种方法并不总是有效,具体取决于您的代码使用的 Java 语言功能.但如果代码编译,它应该可以工作.)
The compilation flags used. There is a -target
compiler flag that tells it to generate code that will run on an older (target) JVM. And the -source
compiler flag tells it to only accept the older JVM's language features. (This approach won't always work, depending on the Java language features used by your code. But if the code compiles it should work.)
类文件使用的库类.如果它使用旧类库中不存在的库类,那么它将不会运行……除非您可以包含一个向后移植类2 的 JAR.您可以通过使用 -bootclasspath
选项针对旧版 Java 的 API 编译代码来避免此问题.
The library classes that the class file uses. If it uses library classes that don't exist in the older class libraries, then it won't run ... unless you can include a JAR that back-ports the classes2. You can avoid this problem by using the -bootclasspath
option to compile your code against the APIs of the older version of Java.
字节码是否取决于创建它的 java 版本?
Does the bytecode depend on the version of the java it was created with?
是的,对上面的点取模.
Yes, modulo the points above.
1 - Java 8 JVMS 声明:Oracle 在 JDK 版本 1.0.2
中的 Java 虚拟机实现支持类文件格式版本 45.0
到 45.3
包括在内.JDK 发布 1.1.*
支持 45.0
到 45.65535
范围内的类文件格式版本.对于 k ≥ 2,JDK 版本 1.k
支持 45.0
到 44+k.0
范围内的类文件格式版本."
1 - The Java 8 JVMS states this: "Oracle's Java Virtual Machine implementation in JDK release 1.0.2
supports class file format versions 45.0
through 45.3
inclusive. JDK releases 1.1.*
support class file format versions in the range 45.0
through 45.65535
inclusive. For k ≥ 2, JDK release 1.k
supports class file format versions in the range 45.0
through 44+k.0
inclusive."
2 - 反向移植也可能有问题.例如:1) 依赖本机代码支持的事情很可能需要您实现该本机代码支持.2) 当您在旧版 JVM 上运行代码时,您很可能需要将任何后向端口 JAR 文件放到引导类路径中.
2 - A backport could be problematic too. For example: 1) Things which depend on native code support would most likely require you to implement that native code support. 2) You would most likely need to put any back-port JAR file onto the bootclasspath when you run the code on the older JVM.
这篇关于如果我使用最新的 JDK 编译 Java 文件,那么旧的 JVM 是否能够运行 .class 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!