0

使用以下代码,

@Option(name = "age") // min = "1"
private int age;

如何验证age字段?说必须大于零?

4

2 回答 2

2

您可以Option在表单的方法上放置注释void methodName(T value)。因此,您可以通过以下方式轻松完成。

private int age;

@Option(name = "age")
void setAge(int age) {
    if (age < 1) {
        throw new CmdLineException("message");
    }
    this.age = age;
}
于 2015-11-05T12:30:26.557 回答
1

我为自己解决了bean-validation.

一旦我像这样注释那些@Options,

class Opts {

    @Option(name = "-buffer-capacity",
            usage = "each buffer's capacity in bytes")
    @Min(1024)
    private int bufferCapacity = 65536;

    @Option(name = "-buffer-count", required = true,
            usage = "number of buffers to allocate")
    @Min(1)
    @Max(1024)
    private int bufferCount;
}

我可以使用bean-validation.

final Opts opts;
final ValidatorFactory factory
    = Validation.buildDefaultValidatorFactory();
final Validator validator = factory.getValidator();
final Set<ConstraintViolation<Opts>> violations
    = validator.validate(opts);
于 2015-11-05T14:53:38.203 回答