ieXcept ieXcept - 5 months ago 14
Java Question

`ElementType.FIELD` vs `ElementType.TYPE_USE`

I not fully understand the difference between annotating variable and annotating its type.
Should I prefer type annotation over declaration annotation in this scenario?

@EmailField // can be used on String or Array/Collection of String-s
private String email;
private @EmailType String email2;
@EmailField
private List<@EmailType String> emails;

@Target(ElementType.TYPE_USE)
@interface EmailType {}

@Target(ElementType.FIELD)
@interface EmailField {}

ck1 ck1
Answer

Type annotations in Java 8 are mainly around to support stronger type checking.

From https://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.html:

Type annotations were created to support improved analysis of Java programs way of ensuring stronger type checking. The Java SE 8 release does not provide a type checking framework, but it allows you to write (or download) a type checking framework that is implemented as one or more pluggable modules that are used in conjunction with the Java compiler.

From your above example, you should use the @EmailField field annotation, and you should also add @Retention(RetentionPolicy.RUNTIME) so that you can use reflection to check for this annotation at runtime as follows:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface EmailField {}
Comments