Can Java 10 compiled classes run on 9? [duplicate]

只愿长相守 提交于 2019-11-28 11:36:52

This has nothing to do with Java 10; the rules are the same as they've always been.

In every version of Java, the classfile version number has been incremented. You can run older classfiles on a newer Java runtime (you can run files compiled twenty years ago under Java 1.0 on Java 10!), but it has never been true that you can run newer classfiles on an older runtime. This hasn't changed with Java 10.

However, you can compile classes such that they run on older versions, if you don't use newer features introduced since that version. This used to be accomplished by the -source and -target switches:

// Run this on Java 8
javac -source 6 -target 6 Foo.java

and you'll get classfiles that will run on Java 6 and later. (The source version cannot be greater than the target version.) This was recently replaced with the more comprehensive --release option:

javac --release 9

which implies not only -source 9 and -target 9, but the compiler will also prevent you from using JDK functionality introduced after 9.

javac has supported a --release argument for a while. As long as you aren't using features from a newer release (in this case Java 10), you can do:

javac --release 9

And everything should work fine. Even better, the Java compiler will complain if there are issues that need to be addressed.

Note that without doing this you will get an UnsupportedClassVersionError even if the code is technically valid because the minimum Java version required is included in the compiled bytecode, and this defaults to the current version of the java compiler.

Nowadays you can also use multirelease jars if you want to use newer java language features but also include code supporting older JVMs.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!