0

当我在 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);

 }
    }

当我构建它时,第三个和第四个选项值被视为空。java -jar testreport-1.0.2-SNAPSHOT.jar -t token -p project -b branch -PR pullreq

代币项目 null

4

1 回答 1

0

问题出在这一行:

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

您只是忘记了给Options实例的相应选项具有长选项属性 of"branchname"而不是 only "branch"。因此,您可以简单地将其更改为:

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

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

于 2021-01-20T12:48:07.403 回答