将这些参数传递给 java 命令行程序的最佳方法是什么?目前,我有用户必须记住的依赖于顺序的参数。我的程序调用如下:
CommandLineRunner EOD 10 true
我希望用户能够执行此操作:
CommandLineRunner runType=EOD threadCnt=10 cleanLogs=true
或者更改参数的顺序。
CommandLineRunner threadCnt=10 runType=EOD cleanLogs=true
我不想为此使用外部库,但如果 java 中有一个好的外部库,请提供一个示例来说明如何使用它来构建我的示例。 =
符号必须存在,因为我需要使该程序遵循我们组织中其他基于 python/ruby 的 cli 应用程序的标准。
提前谢谢您。
最佳答案
您可以在主类之后的命令行中传递参数:
java CommandLineRunner "runType=EOD" "threadCnt=10" "cleanLogs=true"
然后在程序中:
import java.util.*;
public class CommandLineRunner {
public static void main(String args[]){
//Collect the input parameters...
HashMap<String, String> argsMap = new HashMap<String, String>();
for (int i = 0; i < args.length; i++){
StringTokenizer st = new StringTokenizer(args[i], "=");
while(st.hasMoreTokens()) {
String key = st.nextToken();
//Handle the case you don't define a key/value with '='
try{
String val = st.nextToken();
argsMap.put(key, val);
}catch(NoSuchElementException e){
argsMap.put(key, "");
}
}
}
//Then use them when needed...
for (Map.Entry<String,String> entry : argsMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("arg: "+ key + "\tval:" + value);
if(key.equals("runType")){
//Add your business logic here
}
else if (key.equals("threadCnt")){
//Add your business logic here
}
else if (key.equals("cleanLogs")){
//Add your business logic here
}else
//Unknown argument
throw new RuntimeException("Invalid argument!");
}
}
}
因此,无论参数的输入顺序如何,您都会在映射中包含参数。
注意
从Java7
开始,你也可以使用更优雅的switch
结构来处理String
(因此你的参数):
//Then use them when needed...
for (Map.Entry<String,String> entry : argsMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("arg: "+ key + "\tval:" + value);
switch (key) {
case "runType":
//Add your business logic here
break;
case "threadCnt":
//Add your business logic here
break;
case "cleanLogs":
//Add your business logic here
break;
default:
//Unknown argument
throw new RuntimeException("Invalid argument!");
}
}
关于java - 我如何传递这样的参数,例如 : runType=EOD threadCnt=10 cleanLogs=true in my commandline java program?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24036586/