Argument processing using GWT ToolBase

suggest change

If you want to parse more complex command-line arguments, for example with optional parameters, use Google’s GWT approach. The classes are publicly available at:

https://gwt.googlesource.com/gwt/+/2.8.0-beta1/dev/core/src/com/google/gwt/util/tools/ToolBase.java

An example for handling the command-line myprogram -dir "~/Documents" -port 8888 is:

public class MyProgramHandler extends ToolBase {
   protected File dir;
   protected int port;
   // getters for dir and port
   ...

   public MyProgramHandler() {
       this.registerHandler(new ArgHandlerDir() {
            @Override
            public void setDir(File dir) {
                MyProgramHandler.this.dir = dir;
            }
       });
       this.registerHandler(new ArgHandlerInt() {
            @Override
            public String[] getTagArgs() {
               return new String[]{"port"};
            }
            @Override
            public void setInt(int value) {
               MyProgramHandler.this.port = value;
            }
       });
   }
   public static void main(String[] args) {
      MyProgramHandler myShell = new MyProgramHandler();
      if (myShell.processArgs(args)) {
         // main program operation
         System.out.println(String.format("port: %d; dir: %s",
            myShell.getPort(), myShell.getDir()));
         System.exit(0);
      }
      System.exit(1);
   }
}

ArgHandler also has a method isRequired(), which can be overridden to mark the command-line argument as required. The default return is false, so the argument is optional.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents