Search code examples
javagetopt

Java GNU GetOpt: Understanding LongOpt's StringBuffer flag


I don't quite understand the purpose of the third constructor in LongOpt. The overview describes it as follows:

If the flag field in the LongOpt object representing the long option is non-null, then the integer value field is stored there and an integer 0 is returned to the caller.

Excerpt from the above example to guide my observations/questions below:

 LongOpt[] longopts = new LongOpt[3];
 // 
 StringBuffer sb = new StringBuffer();
 longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h');
 longopts[1] = new LongOpt("outputdir", LongOpt.REQUIRED_ARGUMENT, sb, 'o'); 
 longopts[2] = new LongOpt("maximum", LongOpt.OPTIONAL_ARGUMENT, null, 2);
// ...
// See overview link above for full example
// ..
while ((c = g.getopt()) != -1)
  switch (c)
    case 0:
      arg = g.getOptarg();
      System.out.println("Got long option with value '" +
                     (char)(new Integer(sb.toString())).intValue()
                     + "' with argument " +
                     ((arg != null) ? arg : "null"));
      break;
      // ... Rest of example

So when looping through the options you'll get back 0. Of course that does not tell you which option we've hit so we put the "short form" of the long option, o for --outputdir above, into the StringBuilder object, sb. Extracting the char from that StringBuilder option allows you to see which long option it was and know what to do with the argument to that option.

Some questions:

  • Is my understanding above correct?
  • Why use a StringBuilder storing a char? Why not just have a regular string and put the full long option name, i.e. outputdir in that?
  • Why not have the switch statement match on the long option string? I.e. outputdir. Is this because the library was written prior to JDK 7 when you could not switch on Strings? Then long options could be matched much like short options.

Solution

  • After some research I can provide some clarity to my own questions

    Is my understanding above correct?

    I think it is based on experiments. But open to corrections for anyone who reads this in the future.

    Why use a StringBuilder storing a char? Why not just have a regular string and put the full long option name, i.e. outputdir in that?

    Why not have the switch statement match on the long option string? I.e. outputdir. Is this because the library was written prior to JDK 7 when you could not switch on Strings? Then long options could be matched much like short options.

    Yes, the last commit to the only repo I can find is 8 years ago. Hence the need to extract the matched option to a single char for use in the switch statement.

    I have, instead, moved to using Apache Commons CLI which has a much easier API