Search code examples
javaantjavac

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.


Solution

  • 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.