Home > Enterprise >  Purpose of defining an Annotation inside an Annotation in Java
Purpose of defining an Annotation inside an Annotation in Java

Time:02-24

I'm a Java developer going through the code base at the company I work for trying to look for advanced language syntax I'm unfamiliar with. I stumbled across a folder of constraint annotations that all contain annotation definitions within themselves like follows...

@Constraint(validatedBy=MyValidator.class)
@Target(FIELD)
@Retention(RetentionPolicy.RUNTIME)    
@Documented
public @interface FirstAnnotation{ 
    Class<?>[] groups() default{};
    Class<? extends Payload>[] payload() default {};
    String message() default "Default message";

    @Target({FIELD, ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface List {
        FirstAnnotation[] value();
    }
}

Can someone enlighten me as to the purpose of this and how it would be exercised? I get that it is a list of the FirstAnnotation as the value, but not sure what a use case for this would be and how you could use the List annotation. I'm also curious if someone could shine a light on why the groups(), payload(), and message() are required?

CodePudding user response:

It's a static member, which means you can use this:

@FirstAnnotation.List({
    @FirstAnnotation(...),
    @FirstAnnotation(...)
})
private MyType myField;

You can make this even easier by annotating FirstAnnotation with @Repeatable(FirstAnnotation.List.class). That way, you can omit the explicit list:

@FirstAnnotation(...)
@FirstAnnotation(...)
private MyType myField;

As for these three fields, see https://javaee.github.io/tutorial/bean-validation-advanced001.html and https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/validator-customconstraints.html.

  • Related