0

With following code,

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

How can I validate age field? Say must be bigger than zero?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

2 Answers2

2

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;
}
1

I solved for myself with bean-validation.

Once I annotated those @Options 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);
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184