Args4j、コマンドライン解析

リフレクション+アノテーションでとても簡単。Commons CLIより高機能だな。

command output.txt -format TXT -limit 100 -flag
enum OutputFormat { TXT, TSV };
public static class Conf {
	@Option(name="-flag",usage="this is the flag")
	public boolean flag=false;

	@Option(name="-limit",metaVar="count",usage="maximum item count")
	public long limit=-1;

	@Option(name="-format",required=true,usage="output format")
	public OutputFormat format;

	@Argument(index=0,usage="output file path",required=true,metaVar="outfile")
	public String outfilepath;
}
public static void main(String[] args) throws Exception {
	Conf conf=new Conf();
	CmdLineParser parser=new CmdLineParser(conf);
	try {
		parser.parseArgument(args);
		//追加の制約。もっとうまい方法があるのかも
		if(conf.flag && conf.format!=OutputFormat.TXT)
			throw new CmdLineException("-flag option is only available in format=TXT");
	} catch(CmdLineException e) {
		System.out.println(e.getMessage());
		parser.printUsage(System.out);
		return;
	}
	// 以下略
}