Apache Commons CLI选项解析器可以忽略未知的命令行选项吗? [英] Can Apache Commons CLI options parser ignore unknown command-line options?

查看:382
本文介绍了Apache Commons CLI选项解析器可以忽略未知的命令行选项吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Java应用程序,它接受使用Apache Commons CLI和GnuParser处理的命令行参数。由于没有兴趣进入的原因,我希望它默默地忽略未知的命令行选项而不是抛出ParseException,但我没有看到这样做的方法。我看到GnuParser.parse()上有一个stopAtNonOption布尔选项,但我想要的更像ignoreAtNonOption,它会在遇到未知令牌后继续处理选项。

I am writing a Java application that takes command line arguments which are processed using Apache Commons CLI with the GnuParser. For reasons that are not interesting to get into, I would like it to silently ignore unknown command line options instead of throwing a ParseException but I don't see a way to do that. I see that there is a stopAtNonOption boolean option on GnuParser.parse() but what I want is more like ignoreAtNonOption where it will keep processing options after encountering an unknown token.

我可以实现我自己的解析器来完成这个但是我很惊讶没有内置这个功能所以我想我会在走这条路之前检查一下。

I could implement my own parser to accomplish this but I'm surprised there isn't this functionality built in so I thought I'd check before going down that road.

我正在谈论的示例代码:

Example code for what I'm talking about:

try {
  CommandLine commandLine = parser.parse(options, args);
  // stopAtNonOption set to true (below) is also not what I want
  // CommandLine commandLine = parser.parse(options, args, true);
} catch (ParseException e) {
  LOG.error("error parsing arguments", e);
  throw new RuntimeException(e);
}


推荐答案

这对我有用(其他解析器也可以派生出来:

This works for me (other parsers can be derived, too):

public class ExtendedGnuParser extends GnuParser {

    private boolean ignoreUnrecognizedOption;

    public ExtendedGnuParser(final boolean ignoreUnrecognizedOption) {
        this.ignoreUnrecognizedOption = ignoreUnrecognizedOption;
    }

    @Override
    protected void processOption(final String arg, final ListIterator iter) throws     ParseException {
        boolean hasOption = getOptions().hasOption(arg);

        if (hasOption || !ignoreUnrecognizedOption) {
            super.processOption(arg, iter);
        }
    }

}

这篇关于Apache Commons CLI选项解析器可以忽略未知的命令行选项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆