Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define one Java annotation in terms of another?

For example, I'd like to have @Nonnegative, defined as @Min(0), and @DaySeconds, defined as @Min(0) @Max(86399).

like image 452
Reuben Thomas Avatar asked Nov 23 '15 10:11

Reuben Thomas


1 Answers

Both @Min and @Max annotations can be used on annotations themselves. This is called constraint composition.

As such, you can define a new constraint DaySeconds like this:

@Min(0)
@Max(86399)
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface DaySeconds {

    String message() default "{your.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

It would be the same for @Nonnegative.

like image 137
Tunaki Avatar answered Oct 16 '22 04:10

Tunaki