Type Annotations in Java

Type Annotations in Java

With the introduction of Java 8, the version has introduced two new features called repeating annotations and type annotations. Until this time, if you wanted to use annotations in Java, you could only do so in the declarations. With Java 8, now you can add annotations to any type use. Wherever you are using a type (includes types in declarations, generics, and casts), you can accompany that with an annotation.

Type Annotation Syntax

Java 8 can declare type annotations on any type use. One example is the snippet below:

@Encrypted String data;
List <@NonNull String> strings;
myGraph = ( @Immutable Graph ) tmpGraph;

You can simply introduce a new type annotation. The process is similar to defining an annotation with the ElementType.TYPE_PARAMETER target, ElementType.TYPE_USE target, or both targets:

@Target ( { ElementType.TYPE_PARAMETER, ElementType.TYPE_USE } )
public @interface Encrypted

The ElementType.TYPE_PARAMETER target signifies that you can write the annotation on the declaration of a type variable (e.g. class MyClass <T> {….}). The Element.Type.TYPE_USE signifies that you can write the annotation on any use type (namely types in declarations, generics, and casts).

You can save annotations in class files, but it does not affect or influence the program’s execution. As an example, you can declare two File variables and a connection as shown in the code below:

File file = ….;
@Encryted File encryptedFile = …;
@Open Connection connection = …;

While you are executing the program, the result will be the same if you pass either of the two files to the connection’s send() method.



Some Examples of Type Annotations

@nonNull List <String>
List <@NonNull String> str
Arrays <@NonNegative Integer> sort
@Encypted File file
@Open Connection connection
void divideInteger (int a, int b) throws @ZeroDivisior ArithmeticException


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.