问题描述
我想创建一个命令,允许用户指定一个可用选项来执行命令。例如,这里是服务列表,命令是状态。用户可以发出命令'status --list Scarlet garnet cardinal' 获取部分服务或'status --all' 获取完整的服务集。我已经实现了以下内容:
@Command(name = "status",description = "checks the status of a service")
public void status(
@Option(names = "--all",description = "checks all services.") boolean all,@Option(names = "--list",arity = "0..1",description = "checks specified services.") boolean list,@Parameters(paramLabel = "<service>",description = "a list of service names") List<String> services) {
if (all) {
System.out.println("check all");
} else if (list) {
System.out.println("check listed");
}
}
它可以工作,但是有一个错误,即如果用户仅提供命令 "status" 而没有任何进一步的参数,则它被认为是有效的。我相信这是因为两个选项都是布尔值。 我们如何纠正此问题以提供至少一个可选选项?
解决方法
我认为您可以通过将 --list
选项从布尔值更改为数组或字符串集合来获得所需的行为。
例如:
@Command(name = "status",description = "checks the status of a service")
public void status(
@Option(names = "--all",description = "checks all services.") boolean all,@Option(names = "--list",arity = "1..*",paramLabel = "<service>",description = "checks specified services.") List<String> services) {
if (all) {
System.out.println("check all");
} else if (services != null && !services.isEmpty()) {
System.out.println("check listed");
}
}
如果选项是互斥的,您可以使用 ArgGroup。
但对于这种情况,也许最简单的解决方案是没有选项,只有要检查的服务列表。如果用户没有指定服务,则应用会检查所有服务。
在代码中:
@Command(name = "status",description = "Checks the status of all services,or only the specified services.")
public void status(
@Parameters(paramLabel = "<service>",arity = "0..*",description = "A list of service names. Omit to check all services.")
List<String> services) {
if (services == null || services.isEmpty()) {
System.out.println("check all");
} else {
System.out.println("check listed");
}
}