前面对 Opetion 已经做了简单介绍,它是用来为应用定义选项,约定应用支持哪些的选项、以及各个选项支持什么类型值的重要对象。
以下是每个 Option 所具有的属性,所有这些都可以使用访问器或使用 OptionBuilder 中定义的方法进行设置。详细如下:

使用 Commons Cli 定义多个选项(短格式和长格式选项),然后输出程序的帮助信息。先看看帮助信息:
$ java Demo2 usage: Demo -b display current time(boolean) -D <property=value> use value for given property(property=value) -f,--file <arg> use given file(File) -s,--size <arg> use given size(Integer) -t,--text <arg> use given information(String)
代码如下:
package com.hxstrive.cli;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
/**
* 使用 Commons CLI 库输出指定程序的使用帮助信息
*
* @author hxstrive.com
*/
public class Demo2 {
public static void main(String[] args) {
// 声明程序选项
Options options = new Options();
// 格式:addOption(
// 选项的简短表示,例如:-t,
// 选项是否拥有值,true-有值,false-没有值,
// 选项描述信息)
options.addOption(new Option("b",
false, "display current time(boolean)"));
// 格式:addOption(
// 选项的简单表示,例如:-t,
// 选项的繁琐表示,例如:-time,
// 选项是否拥有值,true-有值,false-没有值,
// 选项描述信息)
options.addOption(new Option("t", "text",
true, "use given information(String)"));
options.addOption(new Option("s", "size",
true, "use given size(Integer)"));
options.addOption(new Option("f", "file",
true, "use given file(File)"));
// 定义一个属性格式的选项,如: -D name=Hxstrive
Option property = OptionBuilder.withArgName("property=value").hasArgs(2)
.withValueSeparator()
.withDescription("use value for given property(property=value)").create("D");
property.setRequired(true);
options.addOption(property);
// 输出帮助信息
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Demo", options);
}
}运行程序:
$ java Demo2 usage: Demo -b display current time(boolean) -D <property=value> use value for given property(property=value) -f,--file <arg> use given file(File) -s,--size <arg> use given size(Integer) -t,--text <arg> use given information(String)