【问题标题】:validateWith is undefined for the annotation type Parameter (JCommander)validateWith 未定义注释类型参数 (JCommander)
【发布时间】:2021-08-03 18:37:33
【问题描述】:

在尝试使用 JCommander 包的简单示例时,我在 Eclipse 中遇到错误。错误说:

注释类型的属性 validateWith 未定义 参数

我使用的代码如下:

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import com.beust.jcommander.*;
import com.beust.jcommander.validators.PositiveInteger;

public class JCommanderExample {

    @Parameter(names = { "-sp", "-semAndPrec"},  validateWith = CorrectPathValidator.class)
    private Path semAndPrec;

}

当然,我提供了正确路径验证器类,如http://jcommander.org/#Parameter_validation 的文档中所述。

这是课程:

import java.nio.file.Paths;

import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.ParameterException;

public class CorrectPathValidator implements IParameterValidator {
    public void validate(String name, String value) throws ParameterException {
        try {
            Paths.get(value);
        } catch (Exception e) {
            String error = "Parameter " + name + " should be a path (found "
                    + value + ")";
            throw new ParameterException(error);
        }
    }
}

显然我遗漏了一些东西,但http://jcommander.org/#Parameter_validation 的示例似乎与我尝试的相同:

@Parameter(names = "-age", validateWith = PositiveInteger.class)
private Integer age;

谁能告诉我为什么会出现错误?

【问题讨论】:

  • 真的没有人能帮我解决这个问题吗?

标签: java jcommander


【解决方案1】:

我怀疑这是因为您试图解析为一种“路径”类型,这不是 JCommander 的可解析类型之一。此错误似乎表明您的验证器正在尝试验证“路径”类型的“未定义参数”。

要么将参数更改为可自动解析的类型:http://jcommander.org/#Types_of_options,要么实现自定义类型:http://jcommander.org/#Custom_types

那么验证器应该可以工作了。

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 2023-03-09
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2020-03-22
    相关资源
    最近更新 更多