Mars
Mars

Reputation: 4995

Why does Ant compile Java source that has undefined methods for its target Java version

I have the following javac task in Ant. My system environment Java version is Java 8.

<javac destdir="${destination}" deprecation="on" source="1.6" target="1.6" compiler="modern" verbose="true">

In the Java source code I use a method that requires Java 8. If I set the Java version in my system environment to Java 7, then Ant throws an error and will not compile the code.

Why does it compile when my Java version is 8, despite the source and target fields being set 1.6?

When I run the method that is only available in Java 8, I get a NoSuchMethodError, which was expected.

Upvotes: 1

Views: 95

Answers (2)

VGR
VGR

Reputation: 44292

The source version only specifies allowed language features. The target version only specifies the .class file format.

The --release option might do what you want. I haven’t tried it. See the javac documentation.

<javac destdir="${destination}" deprecation="on" release="6" source="1.6" target="1.6" compiler="modern" verbose="true">

Other than that, there is no way for the compiler to know in what version a method was introduced. If it’s available at compile-time, it’s considered valid.

Upvotes: 1

Alexander Petrov
Alexander Petrov

Reputation: 9492

You can compile code of higher version f.ex. 1.8 with compatability or target version a lower version for example 1.6. This will translate the code to byte code compatible with the corresponding version. The reason for this is to be capable of pruducing artifacts compatible with alternative java versions.

This is a built in java function and has nothing to do with ant. Here is equivalent java compiler intruction:

javac -source 1.7 -target 1.5 MyTest.java

The -source defines a minimum version of Java that needs tro be capable of compaling the source code. The condition when using Java 1.8 is met. When using Java 7 the condition is again met, so compilation is attempted , but it eventualy fail because of the Java 8 feature usage.

If you had Java 1.6 then the compilator would have failed imediatly without attempting to perform compilation.

Upvotes: 1

Related Questions