在Java中解析命令行参数的好方法是什么?
当前回答
看一看最近的JCommander。
我创造了它。我很高兴收到问题或功能请求。
其他回答
我想向您展示我的实现:ReadyCLI
优点:
for lazy programmers: a very small number of classes to learn, just see the two small examples on the README in the repository and you are already at 90% of learning; just start coding your CLI/Parser without any other knowledge; ReadyCLI allows coding CLIs in the most natural way; it is designed with Developer Experience in mind; it largely uses the Builder design pattern and functional interfaces for Lambda Expressions, to allow a very quick coding; it supports Options, Flags and Sub-Commands; it allows to parse arguments from command-line and to build more complex and interactive CLIs; a CLI can be started on Standard I/O just as easily as on any other I/O interface, such as sockets; it gives great support for documentation of commands.
我开发这个项目是因为我需要新的功能(选项,标志,子命令),并且可以在我的项目中以最简单的方式使用。
正如前面提到的一个评论(https://github.com/pcj/google-options)是一个很好的开始。
我想补充的一点是:
1)如果您遇到一些解析器反射错误,请尝试使用更新版本的guava。在我的例子中:
maven_jar(
name = "com_google_guava_guava",
artifact = "com.google.guava:guava:19.0",
server = "maven2_server",
)
maven_jar(
name = "com_github_pcj_google_options",
artifact = "com.github.pcj:google-options:jar:1.0.0",
server = "maven2_server",
)
maven_server(
name = "maven2_server",
url = "http://central.maven.org/maven2/",
)
2)当运行命令行时:
bazel run path/to/your:project -- --var1 something --var2 something -v something
3)当你需要使用帮助时,只需输入:
bazel run path/to/your:project -- --help
如果你熟悉gnu getopt,有一个Java端口:http://www.urbanophile.com/arenn/hacking/download.htm。
似乎有一些类是这样做的:
http://docs.sun.com/source/816-5618-10/netscape/ldap/util/GetOpt.html http://xml.apache.org/xalan-j/apidocs/org/apache/xalan/xsltc/cmdline/getopt/GetOpt.html
看看Commons CLI项目,里面有很多好东西。
For Spring users, we should mention also https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/SimpleCommandLinePropertySource.html and his twin brother https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/JOptCommandLinePropertySource.html (JOpt implementation of the same functionality). The advantage in Spring is that you can directly bind the command line arguments to attributes, there is an example here https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/CommandLinePropertySource.html
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 如何从终端/命令行调用VS代码编辑器
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder