如何以优雅的方式做到这一点?
这三个信息(--time=3 --limit=5000 --initDate=2017-01-01.13:00:00)在主类的String[] args中作为特定元素传递。
解析它们确实不是一项复杂的任务(String.substring() 或正则表达式就可以完成这项工作)。
但是一个好的解析器也应该能够不被参数的顺序所困扰,并且还应该考虑在数据映射到特定类型(如日期或数字类型)期间产生相关的调试信息。
最后,添加或删除受支持的参数应该既简单又安全,并且还可能需要获得命令帮助。
因此,首先建议,如果您可以使用库,请不要重新发明轮子并使用
Apache Commons CLI 或更好地使用 arg4j,它使用起来非常简单,避免了样板代码。
如果你不能,至少从他们那里激励你。
Apache Commons CLI 示例
例如创建Options(参数):
public static final String TIME_ARG = "time";
public static final String LIMIT_ARG = "limit";
...
Options options = new Options();
options.addOption("t", TIME_ARG, true, "current time");
options.addOption("l", LIMIT_ARG, true, "limit of ...");
...
然后解析Options 并检索它的值:
public static void main(String[] args) {
...
try{
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
...
// then retrieve arguments
Integer time = null;
Integer limit = null;
LocalDateTime localDateTime = null;
String timeRaw = cmd.getOptionValue(TIME_ARG);
if (timeRaw.matches("\\d*")) {
time = Integer.valueOf(timeRaw);
}
...and so for until you create your object to save
MyObj obj = new MyObj(time, limit, localDateTime);
...
}
catch(ParseException exp ) {
System.out.println( "Unexpected exception:" + exp.getMessage() );
}
}
args4j 示例
args4j 使用起来非常直接。
此外,它提供了一些转换器(从String 到特定类型),但不提供开箱即用的日期转换。
因此,您应该创建自己的处理程序来执行此操作。示例。
在示例中,LocalDateTimeOptionHandler 必须如此实现 [OptionHandler][3]。
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.OptionHandlerFilter;
public class SampleMain {
@Option(name = "--time", usage = "...")
private Integer time;
@Option(name = "--limit", usage = "..")
private Integer limit;
@Option(name="--initDate", handler=LocalDateTimeOptionHandler.class, usage="...")
private LocalDateTime initDate;
public static void main(String[] args) throws IOException {
new SampleMain().doMain(args);
}
public void doMain(String[] args) throws IOException {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("java SampleMain [options...] arguments...");
parser.printUsage(System.err);
System.err.println(" Example: java SampleMain" + parser.printExample(OptionHandlerFilter.ALL));
return;
}
if (time != null)
System.out.println("-time is set");
if (limit != null)
System.out.println("-limit is set");
if (initDate != null)
System.out.println("-initDate is set");
}
}