java 向后兼容性,java 7语言向后兼容性

Brief question: If I use relatively "minor" Java 7 language features previously unavailable in Java 6, such as the try-muticatch block... does this imply that my program won't run in machines with JRE 6 or JRE 5 installed after being compiled as is? If that's correct, is there a quick way to produce a JRE6 .jar executable without changing a Java 7 source code (which, by the way, the only Java 7 feature it would use is the try-multicatch block)?

解决方案

You are correct. Multi-catch is a Java 7 language feature and there is no way to compile it to Java 6 (or earlier) JVM compatible bytecode.

Using a Java 7 compiler, the following allows you to compile Java 6 compatible bytecode:

javac -source 1.6 -target 1.6 MyJavaFile.java

When you attempt to compile a Java 7 language feature (multi-catch, for example) you will get:

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

(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值