编辑:我没有意识到你的意思是使目标(而不是选项)成为必需的。
如果使用完整解析方法CommandLineParser.parse(Options, String[], boolean)
将可选标志设置为 false,则解析器将跳过未知参数。
您可以稍后通过该方法检索它们getArgs()
返回一个 String[]
然后您可以检查这些字符串以确保有一个名为 file.txt 的字符串
Options options = new Options();
options.addOption("b", true, "some message");
String[] myArgs = new String[]{"-b","2", "file.txt"};
CommandLineParser commandParser = new GnuParser();
CommandLine commandline = commandParser.parse(options, myArgs, false);
System.out.println(Arrays.toString(commandline.getArgs()));
会打印[file.txt]
到屏幕上。
因此,您添加一个额外的检查来搜索该数组以查找任何所需的目标:
boolean found=false;
for(String unparsedTargets : commandline.getArgs()){
if("file.txt".equals(unparsedTargets)){
found =true;
}
}
if(!found){
throw new IllegalArgumentException("must provide a file.txt");
}
我同意这很混乱,但我不认为 CLI 提供了一种干净的方法来做到这一点。