Passing command line arguments to Java via ant build script

◇◆丶佛笑我妖孽 提交于 2020-01-02 02:59:05

问题


On running the following command:

ant targetname -Dk1=v1 -Dk2=v2

I want the command line parameters passed down to java, like java whatever -Dk1=v1 -Dk2=v2.

I need to access these parameters from Java code with System.getProperty or System.getenv.

What do I need to write in my ant build script to make this happen?

Or should I take some other approach altogether?


回答1:


I'm not sure exactly how you want to pass these values, but there are several mechanisms:

  • Use <sysproperty> to pass system properties you need to set:
  • Use <arg> to pass command line arguments to your Java class
  • Use <jvmarg> to pass arguments to your Java command itself
  • If you fork your Java task, you can also set environment variables too. These are ignored if you don't fork the Java task

This:

 $ foo=bar; java -Xlingc com.example.foo.bar -Dsys1=fu -Dsys2=barfu -arg1 -arg2 bar

Becomes:

<java classname="com.example.foo.bar"
    fork="true">
    <env key="foo" value="bar"/>
    <sysproperty key="sys1" value="fu"/>
    <sysproperty key="sys2" value="barfu"/>
    <jvmarg value="-Xlingc"/>
    <arg value="-arg1"/>
    <arg value="-arg2"/>
    <arg value="bar"/>
</java>

Hope that example helps




回答2:


Not good in Ant Script but I do something like below :

<target name="execute">
    <echo> Running MyClass ......... </echo>
    <java classname="pkg.MyClass" classpathref="libs">          
        <arg value="val1" /> <!-- command line args -->
        <arg value="val2" />
        <arg value="val3" />
        <env key="k1" value="v1" /> <!-- set environmental value -->
    </java>     
</target>

If you are using Eclipse, you will get suggestions in popup under java tag. I got few more like : <sysproperty/>, <syspropertyset></syspropertyset>, <jvmarg/>




回答3:


Use the nested <arg> elements in your <java> task:

<java classname="test.Main">
     <arg value="${k1}"/>
     <arg value="${k2}"/>
     <classpath>
       <pathelement location="dist/test.jar"/>
       <pathelement path="${java.class.path}"/>
     </classpath>
   </java>


来源:https://stackoverflow.com/questions/14237329/passing-command-line-arguments-to-java-via-ant-build-script

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