Parsing arguments to a Java command line program

后端 未结 9 1039
孤街浪徒
孤街浪徒 2020-12-07 20:37

What if I wanted to parse this:

java MyProgram -r opt1 -S opt2 arg1 arg2 arg3 arg4 --test -A opt3

And the result I want in my program is:

9条回答
  •  忘掉有多难
    2020-12-07 21:30

    You could use https://github.com/jankroken/commandline , here's how to do that:

    To make this example work, I must make assumptions about what the arguments means - just picking something here...

    -r opt1 => replyAddress=opt1
    -S opt2 arg1 arg2 arg3 arg4 => subjects=[opt2,arg1,arg2,arg3,arg4]
    --test = test=true (default false)
    -A opt3 => address=opt3
    

    this can then be set up this way:

    public class MyProgramOptions {
      private String replyAddress;
      private String address;
      private List subjects;
      private boolean test = false;
    
      @ShortSwitch("r")
      @LongSwitch("replyAddress") // if you also want a long variant. This can be skipped
      @SingleArgument
      public void setReplyAddress(String replyAddress) {
        this.replyAddress = replyAddress;
      }
    
      @ShortSwitch("S")
      @AllAvailableArguments
      public void setSubjects(List subjects) {
        this.subjects = subjects;
      }
    
      @LongSwitch("test")
      @Toggle(true)
      public void setTest(boolean test) {
        this.test = test;
      }
    
      @ShortSwitch("A")
      @SingleArgument
      public void setAddress(String address) {
        this.address = address;
      }
    
      // getters...
    }
    

    and then in the main method, you can just do:

    public final static void main(String[] args) {
      try {
        MyProgramOptions options = CommandLineParser.parse(MyProgramOptions.class, args, OptionStyle.SIMPLE);
    
        // and then you can pass options to your application logic...
    
      } catch
        ...
      }
    }
    

提交回复
热议问题