使用以下代码,
@Option(name = "age") // min = "1"
private int age;
如何验证age
字段?说必须大于零?
使用以下代码,
@Option(name = "age") // min = "1"
private int age;
如何验证age
字段?说必须大于零?
您可以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;
}
我为自己解决了bean-validation
.
一旦我像这样注释那些@Option
s,
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);