Java commons-cli,带有可能值列表的选项
如何使选项仅接受某些指定值,如下例所示:
$ java -jar Mumu.jar -a foo
OK
$ java -jar Mumu.jar -a bar
OK
$ java -jar Mumu.jar -a foobar
foobar is not a valid value for -a
How can I make an option accept only some specified values like in the following example:
$ java -jar Mumu.jar -a foo
OK
$ java -jar Mumu.jar -a bar
OK
$ java -jar Mumu.jar -a foobar
foobar is not a valid value for -a
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于 commons-cli 不直接支持这一点,最简单的解决方案可能是在获取选项时检查它的值。
Since commons-cli doesn't support that directly, the simplest solution is probably to check the value of an option when you get it.
另一种方法是扩展 Option 类。在工作中我们做到了:
The other way can be to extend the Option class. At work we have made that:
我以前就想要这种行为,但从未遇到过使用已经提供的方法来做到这一点的方法。这并不是说它不存在。一种蹩脚的方法是自己添加代码,例如:
显然,有比长 if/else 更好的方法来做到这一点,可能使用
enum
,但这应该是你的全部d 需要。我还没有编译这个,但我认为它应该可以工作。此示例也没有强制使用“-a”开关,因为问题中没有指定这一点。
I've wanted this kind of behaviour before, and never came across a way to do this with an already provided method. That's not to say it doesn't exist. A kind of lame way, is to add the code yourself such as:
Obviously there would be nicer ways to do this than the long if/else, possibly with an
enum
, but that should be all you'd need. Also I've not compiled this, but I reckon it should work.This example also does not make the "-a" switch mandatory, since that wasn't specified in the question.