java 7语言向后兼容性

dei*_*rus 8 java backwards-compatibility

简短的问题:如果我使用Java 6中以前不可用的相对"次要"Java 7语言功能,例如try-muticatch块......这是否意味着我的程序不能在安装了JRE 6或JRE 5的机器上运行按原样编译?如果这是正确的,是否可以快速生成JRE6 .jar可执行文件而无需更改Java 7源代码(顺便说一下,它将使用的唯一Java 7功能是try-multicatch块)?

Bri*_*ach 8

你是对的.Multi-catch是一种Java 7语言特性,无法将其编译为Java 6(或更早版本)JVM兼容字节码.

使用Java 7编译器,以下允许您编译Java 6兼容的字节码:

javac -source 1.6 -target 1.6 MyJavaFile.java

当您尝试编译Java 7语言功能(例如,multi-catch)时,您将获得:

roach$ javac -source 1.6 -target 1.6 test.java
warning: [options] bootstrap class path not set in conjunction with -source 1.6
test.java:9: error: multi-catch statement is not supported in -source 1.6
    } catch (NullPointerException | BufferOverflowException ex) {}
                                  ^
  (use -source 7 or higher to enable multi-catch statement)
1 error
1 warning
Run Code Online (Sandbox Code Playgroud)

(For more about what that warning means, see: https://blogs.oracle.com/darcy/entry/bootclasspath_older_source - it's not relavent to this discussion)

If you change the -source flag to 1.7 you will receive:

source release 1.7 requires target release 1.7

Because ... you can't compile Java 7 source (e.g. source that has Java 7 features) to Java 6 compatible bytecode.

If you compile it with Java 7 (with no -source or -target flag) you will get Java 7 bytecode which can not be run on a < Java 7 JVM. And if you try to do so you will receive an error telling you the versions don't match:

roach$ /Library/Java/Home/bin/java net.mostlyharmless.multicatch.App
Exception in thread "main" java.lang.UnsupportedClassVersionError: net/mostlyharmless/multicatch/App : Unsupported major.minor version 51.0


Evg*_*eev 7

你不能将带有Java 7特性的源代码编译成Java 6 .class,因为这样

javac -source 1.7 -target 1.6 Test.java
Run Code Online (Sandbox Code Playgroud)

产生source release 1.7 requires target release 1.7错误.这是因为1.7功能中的某些功能只能用于Java 7类.例如,try-with-resources使用Throwable.addSuppressed方法仅从1.7开始