如何在Java中为命令行参数创建标志? [英] How do you make flags for command line arguments in Java?
问题描述
我有一个25个应用程序的枚举和一些环境的枚举。
I have an enum for 25 applications and an enum for some environments.
现在有了我的代码,我可以不传递任何参数,它运行所有的应用程序在所有环境中(这是我想要的)或者我可以按顺序传递一个应用程序和一个环境。我需要通过像-app app1 app2 app3 ... -env env1 env2 ...
Right now with the code I have I can either pass no arguments and it runs all of the application in all of the environments(which is what I want) or I can pass one app and one environment in that order it will run that. I need to be able to pass a list of apps by doing something like -app app1 app2 app3 ... -env env1 env2...
来传递应用列表我从未使用过之前的标志或尝试解析之前的命令数组。这是代码的一部分。我认为if是好的,但是我需要帮助。
I've never used flags before or tried parsing an array of commands before. Here's part of the code. I think the if is good but the else is where I need help.
public static Application chooseAppTest(String[] args)
{
Application application = null;
switch (Application.valueOf(args[0]))
{
case ACCOUNTINVENTORY:
new AccountInventory(Environment.valueOf(args[1]));
AccountInventory.accountInventoryDatabaseTests(testResults);
break;
public static void main(String[] args)
{
// run tests and collect results
if (args.length == 0)
{
LogIn.loginTest(testResults);
DatabaseTest.testResults(testResults);
LinkTest.linkTests(testResults);
}
else
{
// First choose application, then choose environment
Application.chooseAppTest(args);
}
推荐答案
即使这可能不直接回答你的问题,我强烈建议你使用一个库。一些广泛使用的选项:
Even though this might not directly answer your question, I strongly suggest that you use a library for that. Some widely used options:
- Commons CLI - http://commons.apache.org/proper/commons-cli/
- JCommander - http://jcommander.org/
- JOpt-Simple - http://pholser.github.io/jopt-simple/
- ArgParse4J - http://argparse4j.sourceforge.net/
- Commons CLI - http://commons.apache.org/proper/commons-cli/
- JCommander - http://jcommander.org/
- JOpt-Simple - http://pholser.github.io/jopt-simple/
- ArgParse4J - http://argparse4j.sourceforge.net/
毕竟,生命太短,无法解析命令行参数。例如(使用 JCommander ),您只需要通过注释定义参数:
After all, "life is too short to parse command line parameters". As an example (using JCommander), you just need to define your parameters through annotations:
//class MyOptions
@Parameter(names = { "-d", "--outputDirectory" }, description = "Directory")
private String outputDirectory;
然后使用以下方法解析bean:
And then parse your bean using:
public static void main(String[] args){
MyOptions options = new MyOptions();
new JCommander(options, args);
}
这篇关于如何在Java中为命令行参数创建标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!