命令行参数解析器
用途:对命令行参数进行解析,完成应用程序的配置
比如,启动应用的时候,通过命令行指定端口,如果没有指定,则使用默认的。
package org.apache.commons.cli; public class App { public static void main(String[] args) throws ParseException { test(args); } private static void test(String[] args) throws ParseException { Options options = new Options(); //arg1: 该选项的名称 //arg2: 该选项后面是否需要跟参数。 如,java -jar命令,jar选择后面不需要后面跟参数,即为false //arg3: 该选项的具体描述 options.addOption("t", false, "don't know"); options.addOption("c", true, "specify your country"); CommandLineParser parser = new BasicParser(); //在解析之前,必须将所有选项都设置到options中 CommandLine cmd = parser.parse(options,args); //不带参数值的选项,只检查此选项是否出现 if(cmd.hasOption("t")) System.out.println("命令行参数出现了't'选项"); else System.out.println("t选项没有出现"); //带参数值的选项,选项可以不出现在参数列表中;一旦出现,就必须跟参数,否则报错 //如,Run Configuration中配置Arguments参数,输入: -t -c 中国 String country = cmd.getOptionValue("c"); if(country==null) System.out.println("没有指定参数值,使用默认值,country=China"); else System.out.println("你指定的country="+country); } }
@SuppressWarnings("static-access") private static void withArgs(String[] args) throws ParseException { Option port = OptionBuilder.withArgName("portNumber")//参数名称 .hasArg()//需要指定参数值 .withDescription("listening port")//选项描述 .create("port");//选项名称 Options options = new Options(); options.addOption(port); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if(cmd.hasOption("port")) System.out.println("use specify port: " + cmd.getOptionValue("port")); else System.out.println("use default port:" + 9999); //格式化输出选项 HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("maven", options); }