1

在尝试使用 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;

}

当然,我提供了 CorrectPathValidator 类,如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;

有人可以告诉我为什么我会收到错误吗?

4

1 回答 1

0

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

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

然后验证器应该工作。

于 2015-11-15T13:43:20.460 回答