Freewind @ Thoughtworks scala java javascript dart 工具 编程实践 月结 math python english [comments admin] [feed]

(2013-12-19) 我想向java的main()传入大量参数,怎么做最优雅?

广告: 云梯:翻墙vpn (省10元) 土行孙:科研用户翻墙http proxy (有优惠)

项目中有一些用java写成的可执行的工具,需要调用者传入大量的参数。最开始,我使用的是最传统的方式,直接一个传入参数数组,于是有如下这么壮观的代码:

public static void main(String[] args) {
    String aaa = args[0];
    String bbb = args[1];
    String ccc = args[2];
    String ddd = args[3];
    String eee = args[4];
    String fff = args[5];
    String ggg = args[6];
    String hhh = args[7];
    // do something with these arguments
}


调用者:

java MyTool hello world1 world2 world3 world4 world5 world6 world7


客户同事拿去用后,感觉十分不便,向我抱怨。原来他在写脚本调用的时候,必须反复查看我的java源代码,才知道每个参数是做什么的。写完之后,下次需要修改的时候,又忘了还得来查。而且参数顺序还不能错,个数也不能多不能少,总之就是很麻烦。

我也认识到这个问题确实存在,便问客户同事有没有什么好办法,他给了我这样的例子:

public static void main(String[] args) {
    String aaa = System.getProperty("aaa");
    String bbb = System.getProperty("bbb");
    String ccc = System.getProperty("ccc");
    String ddd = System.getProperty("ddd");
    String eee = System.getProperty("eee");
    String fff = System.getProperty("fff");
    String ggg = System.getProperty("ggg");
    String hhh = System.getProperty("hhh");
    // do something with these arguments
}


调用者:

 java -Daaa=hello -Dbbb=world1 -Dccc=world2 -Dddd=world3 -Deee=world4 -Dfff=world5 -Dggg=world6 -Dhhh=world7 MyTool


客户同事的意思是,这种做法可以“完美”的解决他提到的那几个不便之处,比如:

虽然看起来调用方式跟之前没什么变化,但内涵却更加丰富了,而我们要做的,仅仅是定义一个描述类,和调用三两行代码而已。

这是我目前认为最优雅的解决方案。

Args4j还提供了更加丰富的参数定义及获取等功能,有兴趣的同学可自行google。


对于程序员来说,wordpress怎么都不够好用,哪怕我这次还安装了一个markdown插件。看到代码块里多余的<code>和被错误转义的&lt;了吗?

一些评论

caofei

http://commons.apache.org/proper/commons-cli/

支持各种类型

Commons CLI supports different types of options:

POSIX like options (ie. tar -zxvf foo.tar.gz)
GNU like long options (ie. du –human-readable –max-depth=1)
Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
Short options with value attached (ie. gcc -O2 foo.c)
long options with single hyphen (ie. ant -projecthelp)

comments powered by Disqus