通过ant命令行传递参数的两种: 1、通过 System中的Property传递 2、通过main方法中的args参数传递
直接代码:
ShowProps:
package com.matt;
public class ShowProps {
public static void main(String[] args) {
System.out.println("Now in ShowProps class...");
System.out.println("prop1 = " + System.getProperty("prop1"));
System.out.println("prop2 = " + System.getProperty("prop2"));
System.out.println("prop3 = " + System.getProperty("prop3"));
System.out.println("args = " + args[0]);
System.out.println("user.home = " + System.getProperty("user.home"));
}
}
build.xml:
<?xml version="1.0"?> <project name="sysprops" default="run" basedir="."> <property name="prop1" value="Property 1 from Buildfile"/> <property name="prop2" value="Property 2 from Buildfile"/> <property name="args" value="args"/> <target name="clean"> <delete dir="com"/> </target> <target name="compile"> <javac srcdir="." destdir="."> <classpath path="."/> </javac> </target> <target name="run" depends="compile"> <echo message="Now in buildfile..."/> <echo message="prop1 = ${prop1}"/> <echo message="prop2 = ${prop2}"/> <echo message="user.home = ${user.home}"/> <!-- execute the main() method in a Java class --> <java classname="com.matt.ShowProps"> <classpath path="."/> <!-- pass one of the properties --> <sysproperty key="prop1" value="${prop1}"/> <sysproperty key="prop3" value="${prop2}"/> <arg value="${args}"/> </java> </target> </project>
直接运行ant命令,结果:
[java] Now in ShowProps class...
[java] prop1 = Property 1 from Buildfile
[java] prop2 = null
[java] prop3 = Property 2 from Buildfile
[java] args = args
[java] user.home = C:\Users\matt
运行命令: ant -Dprop1="prop1",-Dprop2="prop2",-Dprop3="prop3",-Dargs="args1,args2,args3,args4"
结果:
[java] Now in ShowProps class...
[java] prop1 = prop1
[java] prop2 = null
[java] prop3 = prop2
[java] args = args1,args2,args3,args4
[java] user.home = C:\Users\matt