简体   繁体   中英

Can i compile java for an older Java version with ant with a newer JDK so it generates output when it compiles code that uses the newer API?

I would like to only have JDK 8 installed on my system, and have the ant javac compile action create working classfiles for a java 6 environment.

This sort of works if I syntactically only use java 6 compliant code, but my code can access methods/classes of the java 8 API and still be java 6 compliant according to ant's compile action.

This is even the case when using the "javac" task attributes "source" and "target" set to java 6. I am aware that this generates the following warning: [javac] warning: [options] bootstrap class path not set in conjunction with -source 1.6. But this is not the type of warning that helps me detect if my code actually uses newly introduced API elements.

I need the compile action to somehow do something when the code that's being compiled tries to make use of java 8 API introduced methods/classes.

As an example: with java 6 compliant code I can access java.lang.reflect.Constructor.getParameters() if copmiled using JDK 8, which is a method inherited from a Java 8 introduced parent class Executable. When the code runs in a java 6 exeuction environment, executing that statement will result in a thrown NoSuchMethodException, unforseen and thusly unhandled as well. I need my ant compile action generate some different kind of output (a halt or a warning or something else) so that I can automate something on that.

Is there an ant-related solution for me in this scenario?

You write:

I am aware that this generates the following warning: [javac] warning: [options] bootstrap class path not set in conjunction with -source 1.6.

This warning points us toward the correct solution. In addition to the -source and -target options, use javac 's -bootclasspath option to specify a bootstrap class path pointing to the rt.jar of 1.6 . You do not have to have a complete JDK 1.6 on you computer; that jar, which contains the API classes, is sufficient.

Oracle has further instructions and options for cross-compiling on its website.

Note that this issue is addressed by JEP 247 , which hopefully will make it into the Java 9 release. Then, there will be a -release compiler option, combining -source , -target and -bootclasspath with an appropriate file shipping with the JDK itself. So you don't need to get that rt.jar from an older JDK anymore.

您必须编码到Java 6 API或查找新库的端口以与您的应用程序打包

You only real option for Java 6+ compatibility is to use the Java 6 compiler. The disk space you save is not worth the worry that it won't actually run on Java 6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM