如何在 Java 的命令行中将参数传递给 main()?
How to pass args to main() in command line in Java?
我有一个主要功能,我想调用 getKey() 方法并通过命令行传递 4 个参数。如何修改代码以传递参数?您能提供一些建议吗?
命令行如下所示:
java -Dlog4j.configuration=logging.properties -classpath ${class_path} --year="2021" --month="2" --day="2" --customerId=1234567
public static void main(String[] args) {
List<String> keys = getKey(year, month, day, customerId);
for (String key : keys) {
....
}
}
How to pass args to main() in command line in Java?
首先,你的命令行不正确。
$ java -Dlog4j.configuration=logging.properties -classpath ${class_path} \
--year="2021" --month="2" --day="2" --customerId=1234567
应该是
$ java -Dlog4j.configuration=logging.properties -classpath ${class_path} \
${class_name} --year="2021" --month="2" --day="2" --customerId=1234567
其中 ${class_name}
是包含您的入口点方法的 class 的全名;例如com.acme.myapp.Main
之类的。有关详细信息,请参阅 。
一旦您更正了上述内容,args 将在 args
参数中作为等同于以下值的值传送:
new String[]{"--year=2021", "--month=2", "--day=2", "--customerId=1234567"}
请注意,shell 将删除原始引号。 (如果你想停止,那么他们需要在命令行上被引用或转义。它发生在 before Java 甚至看到参数。)
现在您的问题是将这些字符串转换为您的程序可以理解的内容。有两种方法:
在自定义Java代码中实现参数解析;例如使用 String.split
、Integer.parseInt
等。
查找并使用 Java 命令行解析器库。 Google 搜索 java command line parser
会给你很多候选人。
如果您想遵守一组现有的约定(例如 https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html),请寻找处理此问题的库。
(请注意,标准 Java SE 库不包含命令行参数解析功能。我猜原因是 OS 命令行参数约定足够多样化,可用 便携式解决方案不可行。)
我有一个主要功能,我想调用 getKey() 方法并通过命令行传递 4 个参数。如何修改代码以传递参数?您能提供一些建议吗?
命令行如下所示:
java -Dlog4j.configuration=logging.properties -classpath ${class_path} --year="2021" --month="2" --day="2" --customerId=1234567
public static void main(String[] args) {
List<String> keys = getKey(year, month, day, customerId);
for (String key : keys) {
....
}
}
How to pass args to main() in command line in Java?
首先,你的命令行不正确。
$ java -Dlog4j.configuration=logging.properties -classpath ${class_path} \
--year="2021" --month="2" --day="2" --customerId=1234567
应该是
$ java -Dlog4j.configuration=logging.properties -classpath ${class_path} \
${class_name} --year="2021" --month="2" --day="2" --customerId=1234567
其中 ${class_name}
是包含您的入口点方法的 class 的全名;例如com.acme.myapp.Main
之类的。有关详细信息,请参阅 。
一旦您更正了上述内容,args 将在 args
参数中作为等同于以下值的值传送:
new String[]{"--year=2021", "--month=2", "--day=2", "--customerId=1234567"}
请注意,shell 将删除原始引号。 (如果你想停止,那么他们需要在命令行上被引用或转义。它发生在 before Java 甚至看到参数。)
现在您的问题是将这些字符串转换为您的程序可以理解的内容。有两种方法:
在自定义Java代码中实现参数解析;例如使用
String.split
、Integer.parseInt
等。查找并使用 Java 命令行解析器库。 Google 搜索
java command line parser
会给你很多候选人。
如果您想遵守一组现有的约定(例如 https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html),请寻找处理此问题的库。
(请注意,标准 Java SE 库不包含命令行参数解析功能。我猜原因是 OS 命令行参数约定足够多样化,可用 便携式解决方案不可行。)