Ror*_*ory 9 java apache-commons apache-commons-cli
我正在使用Apache Commons CLI.默认情况下,它按键按字母顺序命令命令行上的选项.那么,看来是:
-csv
-ip
-msisdn
-xml
Run Code Online (Sandbox Code Playgroud)
但我想按如下顺序排序:
-csv
-xml
-ip
-msisdn
Run Code Online (Sandbox Code Playgroud)
我知道你可以使用一个OptionFormatter类并传递给HelpFormatter,但是看不到任何关于如何将它用于上述目的的例子(http://www.marko.homeunix.org/programming/java/公地-CLI/API /组织/阿帕奇/公地/ CLI/HelpFormatter.OptionComparator.html).
只是想知道有没有人做过类似的事情?
谢谢
Mar*_*mel 16
从v1.3开始,你可以调用setOptionComparator(null),这样格式化程序就会跳过排序,参数的打印顺序与添加顺序相同.
HelpFormatter formatter = new HelpFormatter();
formatter.setOptionComparator(null);
Run Code Online (Sandbox Code Playgroud)
链接到实际问题.
小智 8
而实施这种比较器的最佳KISS方式是:
class OptionComparator<T extends Option> implements Comparator<T> {
private static final String OPTS_ORDER = "abcdef"; // short option names
public int compare(T o1, T o2) {
return OPTS_ORDER.indexOf(o1.getOpt()) - OPTS_ORDER.indexOf(o2.getOpt());
}
}
Run Code Online (Sandbox Code Playgroud)
目前不支持。但它是开源的,所以你知道该怎么做......
从源代码来看:
private static class OptionComparator
implements Comparator {
/**
* <p>Compares its two arguments for order. Returns a negative
* integer, zero, or a positive integer as the first argument
* is less than, equal to, or greater than the second.</p>
*
* @param o1 The first Option to be compared.
* @param o2 The second Option to be compared.
*
* @return a negative integer, zero, or a positive integer as
* the first argument is less than, equal to, or greater than the
* second.
*/
public int compare(Object o1, Object o2)
{
Option opt1 = (Option)o1;
Option opt2 = (Option)o2;
return opt1.getKey().compareToIgnoreCase(opt2.getKey());
}
}
Run Code Online (Sandbox Code Playgroud)
您可以覆盖默认比较器并定义所需的顺序。
| 归档时间: |
|
| 查看次数: |
5643 次 |
| 最近记录: |