cmd输入java未知指令,Apache Commons CLI选项解析器可以忽略未知的命令行选项吗?...

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);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值