Java:将命名和未命名参数的组合传递给可执行的 jar/main 方法 [英] Java: Passing combination of named and unnamed parameters to executable jar/main method

查看:28
本文介绍了Java:将命名和未命名参数的组合传递给可执行的 jar/main 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 namedunnamed 参数传递给 main 方法.

I want to pass, both, named and unnamed arguments to the main method.

目前我将参数传递为:

 java -jar myfile.jar param1 param2

并将它们处理为:

public static void main(String[] args) throws IOException {
    String param1 = args[0];
    String param2 = args[1];
}

但是,我想以更动态的方式传递参数 - 即:

However, I want to pass the arguments in a more dynamic way - namely, so that:

  1. 我可以传递 namedunnamed 参数;
  2. 我可以使用它们的名称来获取/处理这些参数;
  3. 每次执行 main 方法时,我都不需要以相同的顺序传递它们.
  1. I can pass, both, named and unnamed arguments;
  2. I can fetch/handle these arguments with their names;
  3. I will not be required to pass them in the same order, every time I execute the main method.

以某种方式传递 类似这样的事情:

Passing in a way Something like this:

   java -jar myJar param3name=param3 param2name=param2 param1name=param1 param5 param6

并以这样的方式处理:

public static void main(String[] args) throws IOException {
    //something like
    String param3 = getvaluemethod("param3name");
    String param1 = getvaluemethod("param1name");
     .....
    String param5 = args[n]
    String param6 = args[n+1]
     .....
}

我可以使用一些外部库,这会让我的工作更轻松.

I am fine to work with some external libraries which would make my work easier.

我已经看过这个 并不全面.

I have already seen this and it is not comprehensive.

对如何完成任务有任何意见吗?

Any input on how to accomplish the task?

推荐答案

Apache Commons CLI 是我用来解析 java 命令行参数的工具.可以在此处找到示例,可用于执行以下任何操作选项格式:

Apache Commons CLI is what I use to parse java command line arguments. Examples can be found here and can be used to do any of the following option formats:

  • 类似于 POSIX 的选项(即 tar -zxvf foo.tar.gz)
  • GNU 喜欢长选项(即 du --human-readable --max-depth=1)
  • Java 类属性(即 java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • 带值的短选项(即gcc -O2 foo.c)
  • 带单个连字符的长选项(即 ant -projecthelp)

这篇关于Java:将命名和未命名参数的组合传递给可执行的 jar/main 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆