How to change the Java JDK version in an Ant task?

Viewed 62940

I need to compile my source code to be compatible with JRE 1.6. However, when I attempt to set the compiler attribute of the javac task to be javac1.6, Ant will still compile my code with javac1.7. I have also tried setting the compiler version to be "modern" and that did not work.

<target name="compile-tests">
    <javac compiler="javac1.6" includeantruntime="false" srcdir="${test.dir}" destdir="${build.dir}" >
        <classpath refid="class.path" />
    </javac>
</target>

My JAVA_HOME is set to JDK 1.6:

echo $JAVA_HOME
/usr/lib/jvm/java-6-openjdk-amd64/

My ant version is: Apache Ant(TM) version 1.8.2

According to this post, Ant uses its own compiler. How do I override the Ant default?

Also, according to this post and the Ant documentation, I can set the global build.compiler property. What do I set that property to be and how might I do that?

5 Answers

I thought it would be nice to add an updated answer to this question, since I recently dealt with a lot of headaches surrounding this same issue. My specific use case: My computer uses JRE1.8, but I needed ant to target JRE1.7 running on the server. The trick for me was to use the following attributes in combination (referencing the documentation):

  • srcdir: Location of the java files.
  • destdir: Location to store the class files.
  • includeantruntime: Whether to include the Ant run-time libraries in the classpath. It is usually best to set this to false so the script's behavior is not sensitive to the environment in which it is run.
  • source: Java language features accepted by compiler
  • target: Generate class files for specific JVM version (cross-compile).
  • fork: Whether to execute javac using the JDK compiler externally.
  • compiler: The compiler implementation to use.

You don't have to specify the executable file unless you have really specific dependencies (e.g. more recent enterprise version as opposed to latest free version).

Example:

<javac srcdir="${source}"
       destdir="${java.output.dir}"
       includeantruntime="false"
       source="1.7"
       target="1.7"
       fork="yes"
       compiler="javac1.7">
</javac>
Related