本文概览:在命令行通过java命令来执行一个程序传入参数时,为了方便使用这个参数来初始化成员变量,引入了args4。
1背景
1、一个例子
1 2 3 4 5 6 7 8 |
public class Demo { public static void main(String[] args){ if(null != args && args.length > 0) { System.out.println(args[0]); System.out.println(args[1]); } } } |
此时在终端执行java命令为
1 |
java -classpath ./target/classes/ shell/Demo 3456 20170320999323ac |
结果如下
3456
20170320999323ac
2、引入args4j
为了能够根据命令行传来的参数初始化成员变量,此时引入了args4j,可以在输入参数中指明变量名字和对应的值。
2 实例
1、maven
1 2 3 4 5 |
<dependency> <groupId>args4j</groupId> <artifactId>args4j</artifactId> <version>2.33</version> </dependency> |
2、@option
- name 参数名字
- required 是否必需
- useage 注释信息
3、代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package shell; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; public class Runner { @Option(name = "-userId", required = true, usage = "用户id") private String userId; @Option(name = "-transId", required = false, usage = "交易单id") private String transId; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getTransId() { return transId; } public void setTransId(String transId) { this.transId = transId; } public void output() { System.out.println("userId=" + userId); System.out.println("transId=" + transId); } public static void main(String[] args) { Runner runner = new Runner(); CmdLineParser parser = new CmdLineParser(runner); try { parser.parseArgument(args); runner.output(); } catch (Exception e) { System.err.println(e.getMessage()); } } } |
输入如下命令
1 |
java -Dfile.encoding=UTF-8 -classpath "/Library/maven/repository/args4j/args4j/2.33/args4j-2.33.jar:/Users/wuzhonghu/Project/me/javabase/target/classes" shell.Runner -userId=3456 -transId=20170320999323ac |
或者直接在IDE配置输入参数
执行结果为
userId=3456
transId=20170320999323ac
(全文完)