Tuesday, January 6, 2015

Java Annotation Retention

Annotation Retention Policy

Java annotation works by adding some code to the java file or the compiled java class file. The notation used is the @Retention tag.

The following is the overall picture:
Source File( A.java) --> Compiled bytecode(A.class) --> Runtime memory after loaded by classloader

There are 3 Retention policies. In the following, we use a '*' to indicate that some annotation code has been inserted.

@Retention(RetentionPolicy.SOURCE)
A*.java --> A.class --> A-runtime

@Retention(RetentionPolicy.CLASS)
A*.java --> A*.class --> A-runtime
This is the default policy.

@Retention(RetentionPolicy.RUNTIME)
A*.java --> A*.class --> A*-runtime.
This is generally used for customer annotations.

Java Annotation Implementation

Java annotation is not part of the java standard edition. You can see that the package is javax.annotation. So a java server container such as Weblogic server and Tomcat serfver is generally needed for the annotation to work. The server container has to implement the annotation artifacts so it knows how to parse, compile and run the java classes with the annotations. Of course, you can also put the needed library for annotation on the classpath to run the java programs with annotations successfully without using a sever container.

No comments:

Post a Comment