【问题标题】:how to preserve argument ordering in help sections?如何在帮助部分保留参数顺序?
【发布时间】:2014-10-10 14:28:38
【问题描述】:

我有以下参数要添加到 CLI
-sbx
-CSWConfig
-stripInfo
-modelSources
-catchArchive
-swSupplierName
-modelsSWExchnage

但在显示帮助时,它会按我不想要的排序顺序(如下所示)显示这些选项,我希望所有选项在添加时都按顺序排列。
-CatchArchive
-CSWConfig
-modelSources
-sbx
-stripInfo
-swSupplierName

我为此阅读了一份link,但在显示帮助内容时无法保留顺序。

private void print_help() {
    String CONST_STR_CLI_INFO = "ercli.exe custzip";
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            Option op1=(Option) o1;
            Option op2=(Option) o2;
            return //what to do here?
        }
    });
    formatter.printHelp(CONST_STR_CLI_INFO, null, options, "", true);
}

【问题讨论】:

  • link 第四个答案给出了 return opt1.getKey().compareToIgnoreCase(opt2.getKey());你会明白的。

标签: java apache-commons-cli


【解决方案1】:

由于 Options() 类在内部将选项存储在 Maps 中,因此它不保留任何顺序。这意味着您需要提供自己的订单,因为您已经知道了。

要获得排序,您可以预先将键放在 List 中,以便为每个元素提供所需顺序的索引:

final List<String> optionKeys = new ArrayList<>();

optionKeys.add("sbx");
optionKeys.add("CSWConfig");
optionKeys.add("stripInfo");
optionKeys.add("modelSources");
optionKeys.add("catchArchive");
optionKeys.add("swSupplierName");
optionKeys.add("modelsSWExchnage");

然后在 Comparator 中,您可以按此列表中的索引进行比较:

    @Override
    public int compare(Object o1, Object o2) {
        Option op1=(Option) o1;
        Option op2=(Option) o2;
        return Integer.compare(optionKeys.indexOf(op1.getLongOpt()), optionKeys.indexOf(op1.getLongOpt()));
    }

【讨论】:

  • 感谢您的帮助,但是我们将如何在此语句中获取密钥 optionKeys.indexOf(o1.key),我收到“o1.key”错误
  • @centic 我也有类似的问题here 使用 Apache Commons CLI。如果可能的话,你能帮帮我吗?
猜你喜欢
  • 2020-10-12
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
相关资源
最近更新 更多