"属性"选项在命令行上由其名称及其对应的属性表示,类似于java属性文件的语法.考虑以下示例,如果我们传递-DrollNo = 1 -Dclass = VI -Dname = Mahesh之类的选项,我们应该将每个值作为属性处理.让我们看看实现逻辑的实际效果.
示例
CLITester.java
import java.util.Properties;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.CommandLineParser;import org.apache.commons.cli.DefaultParser;import org.apache.commons.cli.Option;import org.apache.commons.cli.Options;import org.apache.commons.cli.ParseException;public class CLITester { public static void main(String[] args) throws ParseException { Options options = new Options(); Option propertyOption = Option.builder() .longOpt("D") .argName("property=value" ) .hasArgs() .valueSeparator() .numberOfArgs(2) .desc("use value for given properties" ) .build(); options.addOption(propertyOption); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse( options, args); if(cmd.hasOption("D")) { Properties properties = cmd.getOptionProperties("D"); System.out.println("Class: " + properties.getProperty("class")); System.out.println("Roll No: " + properties.getProperty("rollNo")); System.out.println("Name: " + properties.getProperty("name")); } } }
输出
传递时运行文件选项作为键值对并查看结果.
java CLITester -DrollNo=1 -Dclass=VI -Dname=MaheshClass: VIRoll No: 1Name: Mahesh