Java GNU GetOpt:了解 LongOpt 的 StringBuffer 标志

Java GNU GetOpt: Understanding LongOpt's StringBuffer flag

不太明白LongOpt. The overview中第三个构造函数的用途描述如下:

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.

从上面的示例中摘录以指导我在下面的 observations/questions:

 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

所以当遍历选项时,你会得到 0。当然,这并不能告诉你我们点击了哪个选项,所以我们把长选项的 "short form",o对于上面的 --outputdir,进入 StringBuilder 对象,sb。从该 StringBuilder 选项中提取 char 允许您查看它是哪个长选项并知道如何处理该选项的参数。

一些问题:

经过一些研究,我可以澄清我自己的问题

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.

是的,我能找到的唯一回购的最后一次提交是 8 years ago。因此需要将匹配的选项提取到单个 char 以用于 switch 语句。

我转而使用 Apache Commons CLI,它更容易 API