Run ant task in different jvm

白昼怎懂夜的黑 提交于 2019-11-29 02:26:36
Christopher Peisert

To make Jeanne Boyarsky's suggestion of using the exec Ant task concrete, the following example wraps the exec task in a macro to simplify calling targets with various JVMs. Notice that the JVM is set using the Ant environment variable JAVACMD.

Example Project

<?xml version="1.0" encoding="UTF-8"?>
<project name="run-target-with-specified-java-version" default="test">

  <macrodef name="exec-target">
    <attribute name="antfile" default="${ant.file}" />
    <attribute name="target" />
    <attribute name="jvm" default="${java.home}/bin/java" />
    <sequential>
      <exec executable="ant">
        <env key="JAVACMD" value="@{jvm}" />
        <arg line='-f "@{antfile}"' />
        <arg line="@{target}" />
      </exec>
    </sequential>
  </macrodef>


  <target name="echo-java-version">
    <echo message="Java version: ${java.version}" />
  </target>


  <target name="test">
    <exec-target target="echo-java-version" />

    <property name="java1.6"
        location="/usr/lib/jvm/jdk1.6/bin/java" />
    <exec-target target="echo-java-version" jvm="${java1.6}" />
  </target>
</project>

Output

test:
     [exec] Buildfile: /home/your/project/build.xml
     [exec] 
     [exec] echo-java-version:
     [exec]      [echo] Java version: 1.7.0
     [exec] 
     [exec] BUILD SUCCESSFUL
     [exec] Total time: 0 seconds
     [exec] Buildfile: /home/your/project/build.xml
     [exec] 
     [exec] echo-java-version:
     [exec]      [echo] Java version: 1.6.0
     [exec] 
     [exec] BUILD SUCCESSFUL
     [exec] Total time: 0 seconds

BUILD SUCCESSFUL
Total time: 2 seconds

You can use the exec task to run the build file with that target defined to run as a parameter. It could be running in a different JVM since you can pass the JVM to that exec call.

Note that you'd have to refactor the target to rely on files for communication rather than setting properties. Since it would be in a different JVM, it obviously can't rely on memory.

You can run a target in a different JVM (we do it all the time). You just need to use fork:

  <javac srcdir="${src}"
         destdir="${build}"
         fork="yes"
  />

But I sense you are aware of this, so how about running the external ANT task as it is, and rest of them (lets say you have 3 more javac tasks) in the JVM you want. This can be achieved by setting a property file. See javac task

It is possible to use different compilers. This can be specified by either setting the global build.compiler property, which will affect all tasks throughout the build

So this property will affect your 3 tasks and run them in the JVM you specified (say 1.7) and you can set the default JAVA_HOME to whatever your external library task needs.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!