Furetur
Furetur

Reputation: 471

Run Ant task from Ant with custom JAVA_HOME and java.home

Context

I'm upgrading the version of Java from 8 to 17 in a repository that depends on a library. I want to build the repository with Java 17, but the library with Java 8 because it cannot be built with Java 8.

Environment

Docker container with Java 17, but also with Java 8.

Question

The repository builds the library by running ant tasks in that library

<ant dir="${lib-build-top}" target="all"/>
<ant dir="${lib-build-top}" target="buildjars"/>

In the terminal the library can be built with

JAVA_HOME=path/to/jdk8 ant

So I want to be able to do something like

set JAVA_HOME and java.home from jdk17 to jdk8
<ant dir="${lib-build-top}" target="all"/>
<ant dir="${lib-build-top}" target="buildjars"/>
change JAVA_HOME and java.home back to jdk17

How can I do that?

Upvotes: 2

Views: 340

Answers (1)

VGR
VGR

Reputation: 44414

I think the only way to do this is to fork a new Ant process with a different JAVA_HOME environment variable. There’s even an example of running Ant this way in the documentation of <exec>:

<condition property="jdk8-home"
           value="C:\Program Files\Java\jdk1.8.0_301">
    <os family="windows"/>
</condition>
<property name="jdk8-home" location="/usr/lib/jvm/java-8-openjdk-amd64"/>

<property name="ant-executable" location="${ant.home}/bin/ant"/>

<exec osfamily="unix" executable="${ant-executable}">
    <arg value="-buildfile"/>
    <arg file="${ant.file}"/>
    <arg value="all"/>
    <env key="JAVA_HOME" file="${jdk8-home}"/>
</exec>
<exec osfamily="windows" executable="cmd">
    <arg value="/c"/>
    <arg file="${ant-executable}.bat"/>
    <arg value="-buildfile"/>
    <arg file="${ant.file}"/>
    <arg value="all"/>
    <env key="JAVA_HOME" file="${jdk8-home}"/>
</exec>

<exec osfamily="unix" executable="${ant-executable}">
    <arg value="-buildfile"/>
    <arg file="${ant.file}"/>
    <arg value="buildjars"/>
    <env key="JAVA_HOME" file="${jdk8-home}"/>
</exec>
<exec osfamily="windows" executable="cmd">
    <arg value="/c"/>
    <arg file="${ant-executable}.bat"/>
    <arg value="-buildfile"/>
    <arg file="${ant.file}"/>
    <arg value="buildjars"/>
    <env key="JAVA_HOME" file="${jdk8-home}"/>
</exec>

Upvotes: 1

Related Questions