With following code,
@Option(name = "age") // min = "1"
private int age;
How can I validate age
field? Say must be bigger than zero?
With following code,
@Option(name = "age") // min = "1"
private int age;
How can I validate age
field? Say must be bigger than zero?
You can place Option
annotation on the method of the form void methodName(T value)
.
So you can easily do it in the following way.
private int age;
@Option(name = "age")
void setAge(int age) {
if (age < 1) {
throw new CmdLineException("message");
}
this.age = age;
}
I solved for myself with bean-validation
.
Once I annotated those @Option
s like this,
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;
}
I can validate it using bean-validation
.
final Opts opts;
final ValidatorFactory factory
= Validation.buildDefaultValidatorFactory();
final Validator validator = factory.getValidator();
final Set<ConstraintViolation<Opts>> violations
= validator.validate(opts);