当前位置: 代码迷 >> java >> JCommander参数验证了解其他参数
  详细解决方案

JCommander参数验证了解其他参数

热度:99   发布时间:2023-07-17 20:08:35.0

我正在使用JCommander解析命令行参数。 我使用以下方法验证参数:

public class SomeClass implements IParameterValidator {
    public void validate(String name, String value) throws ParameterException { 
    ...
}

我遇到了一些极端情况,如果上面的代码块可以知道为应用程序提供的其他命令行参数(而不仅仅是该参数)会有所帮助。 JCommander完全可能吗?

我可以使用JCommander Commands实现我的目标,但是这不如所需的解决方案灵活。

我通过将变量进行测试以实现静态。 例如:

@Parameter(names = {"big"}, description = "This must be greater than small", validateValueWith = GreaterThanSmall.class)
private Long big = 10000L;

@Parameter(names = {"small"}, description = "Small")
private static Long small = 10L;

public static class GreaterThanSmall implements IValueValidator<Long> {
    @Override
    public void validate(String name, Long value) throws ParameterException {
        if (value < small) {
            throw new ParameterException("Parameter " + name + " should be greater than small (found " + value +")");
        }
    }
}

该文档明确指出,没有特定的注释可以对提供的参数进行全局验证。

建议在参数解析后进行验证。