问题
I have an enum for 25 applications and an enum for some environments.
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...
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);
}
回答1:
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/
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;
And then parse your bean using:
public static void main(String[] args){
MyOptions options = new MyOptions();
new JCommander(options, args);
}
来源:https://stackoverflow.com/questions/25018205/how-do-you-make-flags-for-command-line-arguments-in-java