Ant: Compiling Using Specific JDK


The Problem
In some cases, when use ant to compile code, we may have to use a specific JDK version which may be different than the default jdk in the system: for example, the project may use some jdk internal code which is not good, but sometimes we have to deal with the legacy project. 
Solution 1: Using JAVACMD Environment Variable
We can define a system environment variable: JAVACMD which points to full path of the Java executable. Ant will use the JVM defined by JAVACMD instead of JAVA_HOME/bin/java
set "JAVACMD=C:\Program Files\Java\jdk1.6.0_45\bin\java.exe"

export "JAVACMD=/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home/jre/bin/java"

But this will make all ant project uses same JVM defined by JAVACMD.
Solution 2: Using javac executable and fork
We can define specify system environment to specific JDK, for example JAVA6_HOME to point to JDK6.
Then in the ant build.xml, define a property env.java.home which point to JAVA6_HOME, then in javac task, set fork=yes and sepecify executable to ${env.java.home}/bin/javac

  <property environment="env"/>
 <property name="env.java.home" value="${env.JAVA6_HOME}"/>
 <javac destdir="${dest-path}/main" fork="yes" executable="${env.java.home}/bin/javac" source="1.6" target="1.6" debug="on" encoding="utf8" classpathref="common.classpath">
  <src path="./src/main" />
 </javac>
javac executable
Complete path to the javac executable to use in case of fork="yes". Defaults to the compiler of the Java version that is currently running Ant. Ignored if fork="no".

Resources
Running Apache Ant
Ant javac

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)