Can I specify the JDK path to compile against within an Ant build.xml?

inger picture inger · Feb 13, 2011 · Viewed 8.6k times · Source

I would like to use JDK 1.6 for a branch of a project while others keep using JDK 1.5. Developers want to occasionally switch between those.

So what is the best way to tell Ant's javac which JDK to use? By best, I mean a robust, transparent, low maintenance, versioned together with the source (Ant itself and JDK are certainly not, but they live at standard places).


The obvious -rather than best- way I guess would be outside of Ant: keep changing the JAVA_HOME env variable. However this would require developers to manually switch (another thing to remember: error prone), an changing all the -many- build servers (more work for me now).

Looking for some simple javac attribute e.g jdk-path, I noticed several instead (thanks to reading up on the net and in SO):

  • compiler- fair enough, but docs says "modern: .. javac1.5 and javac1.6 .. as aliases".. To me this suggests it won't make in any difference - will it?
  • source- seems only related to JLS version (althought not %100 clear from the docs linked above)
  • target - bytecode version
  • bootclasspath - some SO answers mention this, but pretty unclear and seems hackish
  • executable - path to javac, but not to libs.. -- seems the closest match, implicitly specifying JDK path? UPDATE: confirmed by JB Nizet
  • fork - it seems I'll need true here (otherwise it'll just ignore the above without error?). UPDATE: Any performance implications vs. default? (I guess JVM startup times are better these days, but still)

So, it seems none of these help in itself.. is any combination of these equivalent to setting JAVA_HOME prior to running Ant?

I have some hacks in mind (eg wrapping ant executable on each platform just to set that env var - quite sad), but I really hope I missed something :)

Answer

JB Nizet picture JB Nizet · Feb 13, 2011

Using the executable attribute needs to set the fork attribute to true. This means that the javac ant task will launch an external process to execute javac.

When you launch javac manually, you don't have to specify any specific JDK lib directory: it knows where to find the libraries of the JDK it's part of. I'd say it will be the same if you launch it through ant's javac task (unless you override the bootclasspath).