这是使用apache CommandLineParser的示例代码
public class Foo {
public static void main(final String[] args) throws Exception {
Options options = new Options();
options.addOption("x",
true, "comment for param x");
options.addOption("y",
true, "comment for param y");
CommandLine commandLine = null;
CommandLineParser parser = new PosixParser();
try {
commandLine = parser.parse(options, args);
} catch (ParseException e) {
throw new RuntimeException("Error parsing arguments!");
}
if (!commandLine.hasOption("x")) {
throw new IllegalArgumentException("x"
+ " option is missing!");
}
String numberOfColumns = commandLine.getOptionValue("x");
:
:
}
JUNIT测试代码:
@Test
public void testFoo() throws Exception {
args = new String[2];
args[0] = "x" + "=" + "hello";
args[1] = "y" + "=" + "world";
Foo.main(args);
}
我的问题/问题:
CommandLineParser一直抱怨“缺少x选项!”。因此,我相信将参数及其值传递给命令行解析器的方式是错误的。我也尝试了其他方法。
args[0] = "-x" + "=" + "hello";
args[1] = "-y" + "=" + "world";
并且
args[0] = "x"
args[1] = "hello";
args[2] = "y"
args[3] = "world";
有人可以告诉我传递参数及其值的正确格式以便成功吗?
提前致谢。
最佳答案
据我所知,参数必须以减号开头。
args[0] = "-x";
args[1] = "hello";
args[2] = "-y";
args[3] = "world";