ieXcept ieXcept - 1 year ago 174
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;
private List<@EmailType String> emails;

@interface EmailType {}

@interface EmailField {}

ck1 ck1
Answer Source

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


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:

@interface EmailField {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download