Java Annotation

Annotation in Java is there to make programmers life a bit easy.
Annotation-based development relieves Java developers from the pain of cumbersome configuration.

Advantages of using Annotations
  • Annotations are attached to Classes and can be processed via reflection.
  • It is much easier to see the Annotations as they are defined in Java code and no need to refer external configurations (like XML).
  • Compiler will do static type checking for Annotation uses. Compile time the proper uses of annotation will be done.
Here are some rules-of-thumb when defining an annotation type:

Annotation declaration should start with an 'at' sign like @, following with an interface keyword, following with the annotation name.
Method declarations should not have any parameters.
Method declarations should not have any throws clauses.
Return types of the method should be one of the following:
  • primitives
  • String
  • Class
  • enum
  • array of the above types

The following shows example of deceleration an annotation.
1
2
3
4
5
public @interface RestAPIRequestLog {
    int id();
    String requestIp();
    String requestLanguage(); default "[en]"; 
}

An annotation type with no elements is termed a marker annotation type, for example:

public @interface RestAPIMonitored { }

In annotations with a single element, the element should be named
value, as shown below:


1
2
3
public @interface SecuredRestAPI {
 String token();
}

Comments

Popular posts from this blog

Converting Java Map to String

Invoking EJB deployed on a remote machine

Difference between volatile and synchronized