命令行处理共有3个阶段:definition、parsing、interrogation

定义阶段

有2种创建Options实例的方法:一个是通过Options构建器创建,一个是通过Options的工厂方法创建。

创建Option

// create Options object
Options options = new Options();

// add t option
options.addOption("t", false, "display current time");

addOptions方法有3个参数:

  • 第1个参数表示命令选项

  • 第2个参数表示选项是否含有参数

  • 第3个参数是选项的描述

解析阶段

文本的解析方式由parser实现决定。在CommandLineParser中的parse方法,会接收Options实例和参数的String[],返回CommonLine实例。

CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);

上面代码基于common-cli 1.4

问诊阶段

CommandLine实例的accessor方法提供问诊能力,它会根据Options和Parser定义的规则向用户反馈信息。

比如,检验t选项是否存在

if(cmd.hasOption("t")) {
    // print the date and time
}
else {
    // print the date
}

带参选项

上面3个过程,都是以bool选项为例说明,现在说明一下带参数的选项。

定义选项

// add c option
options.addOption("c", true, "country code");

获取参数值

// get c option value
String countryCode = cmd.getOptionValue("c");

if(countryCode == null) {
    // print default date
}
else {
    // print date for country specified by countryCode
}

results matching ""

    No results matching ""