dagblog.
← Archive

Advanced annotations


If you define an annotation of your own in Java, you’ll probably notice that annotations have a syntax of their own and restrictions on the object types they can use. One consequence is that you can use another annotation inside your own. The most elaborate example of what an annotation definition can look like that I’ve seen so far is in the Bean Validation specification (JSR 303). The example below shows how you can map the attributes of one annotation to those of another, which strikes me as an interesting use case.

@NotNull

@Size

@ConstraintValidator(FrenchZipcodeValidator.class)

@Documented

@Target( { ANNOTATION_TYPE, METHOD, FIELD })

@Retention(RUNTIME)

public @interface FrenchZipcode {

 String message() default "Wrong zipcode";



 Class[] groups() default {};



 @OverridesParameters( {

 @OverridesParameter(constraint = Size.class, parameter = "min"),

 @OverridesParameter(constraint = Size.class, parameter = "max") })

 int size() default 5;



 @OverridesParameter(constraint = Size.class, parameter = "message")

 String sizeMessage() default "{beancheck.zipcode.size}";

}

And what is it for?

Parameters from composing annotations can be overridden by parameters from the main
annotation. The parameter value from the main annotation annotated with @OverridesParameter is applied to the parameter named after OverridesParameter.parameter of the composing constraint of type OverridesParameter.
constraint. If not specified, the name of the targeted parameter equals the name of the parameter the
@OverridesParameter is on The types of the overridden and overriding parameters must be equals.

Medium version

Related articles

Related CZ Podcast episodes