Annotations and Decorators in Java

Annotations on the code or decorators have become very common. They allow the programmer to add additional useful information about how to improve the code or change how to compile / run a particular class. They are a Java extension to allow aspect-oriented programming.

We have three types of annotations based on the moment of usage:

Information for the Compiler

These annotations allow the compiler to indicate whether or not to ignore errors and warnings or what to do with them. If you’ve worked with a Java IDE (like eclipse) probably you would have used this type of annotations. For example, you can use @Override on a function to indicate that you are overwriting a method defined on a parent class. 

This annotation is completely optional, but allows both the compiler and the developer to check that they are indeed overwriting existing hierarchical functionality.

For example:

public class Parent {     
    public void do(){
        System.out.println("Parent");
     }
}

public class Son extends Parent{     
    @Override
    public void do(){
        System.out.println("Son");
     }
}
Compiler-time and deployment-time processing

These annotations allow the compiler to add extra information about how to generate the code. By adding or modifying functionality from that in the source code you can alter how a class behaves. Also to create new classes (based on a file descriptor), etc …

These annotations will only be visible at this point. They are not compiled to the .class files. Therefore they are not available at runtime.

Runtime Annotations

You can use this annotations on runtime and they work on a very similar way as an interface.

Let’s see an example on how to create a Runtime Annotation and how can we use it. The annotation named MyAnnotation can be applied to elements oftype field:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
     public @interface MyAnnotation {
}

Now we can create an annotated class by this annotation:

public class myObject
 {
 @MyAnnotation
 public String field;
 }

This way, we can check by reflection if an object has an annotated field on any part of the code:

Class<?> res = objeto.getClass();
for (Field f : res.getFields()) {
     if (f.isAnnotationPresent(MyAnnotation.class)) {
          System.out.println("OK");
      }
}

More Information: