当我使用 apache commons CLI 传递三个以上的选项时..结果显示为第三个选项的 NULL

When I pass more than three options using apache commons CLI..the result is displaying as NULL for third option

当我在 cmd 中传递超过三个选项时..结果显示为 NULL

 package main.java;
import org.apache.commons.cli.*;

public class cli {

    public static void main(String[] args) throws Exception {
         Options options = new Options();
     Option token = new Option("t", "token", true, "token");
     token.setRequired(true);
     options.addOption(token);

     Option projectname = new Option("p", "projectname", true, "project");
     projectname.setRequired(true);
     options.addOption(projectname);
     
     Option branch = new Option("b", "branchname", true, "branch");
     branch.setRequired(true);
     options.addOption(branch);
     
     Option pullreq = new Option("PR", "pullreq", true, "pullreq");
     pullreq.setRequired(true);
     options.addOption(pullreq);
     CommandLineParser parser = new DefaultParser();
     HelpFormatter formatter = new HelpFormatter();
     CommandLine cmd = null;

     try {
         cmd = parser.parse(options, args);
     } catch (ParseException e) {
         System.out.println(e.getMessage());
         formatter.printHelp("utility-name", options);

         System.exit(1);
     }

     String token1 = cmd.getOptionValue("token");
     String projectname1 = cmd.getOptionValue("projectname");
     String branch1 = cmd.getOptionValue("branch");
     String pullreq1 = cmd.getOptionValue("pullreq");
     
   /*if(pullreq != null){
         String pullreq1 = cmd.getOptionValue("pullreq");
         System.out.println(pullreq1);
     }
     */
     System.out.println(token1);
     System.out.println(projectname1);
     System.out.println(branch1);

 }
    }

我建的时候把第三个和第四个选项的值取为null。 java -jar testreport-1.0.2-SNAPSHOT.jar -t token -p project -b branch -PR pullreq

令牌 项目 空

问题出在这一行:

String branch1 = cmd.getOptionValue("branch");

您只是忘记了给定 Options 实例的相应选项有一个 "branchname" 的长选项 属性 而不是只有 "branch"。所以你可以简单地把它改成:

String branch1 = cmd.getOptionValue("branchname");

它会起作用的。至少对我来说是这样。