Wednesday 29 February 2012

Annotations






What is Annotation?
Annotations are nothing but  meta-data added to the Java Elements.   Annotations define a java type exactly similar to Classes,Enums,Interfaces and they can be applied to several Java Elements.

How Custom Annotation are created?
Annotation is defined using @ along with interface keyword.There are two meta annotations required to create custom annotationas shown in example below.

          @Target(ElementType.CLASS)
          @Retention(RetentionPolicy.CLASS)
          public @interface Author
          {
                   String name();
          }

The Meta-Annotations that would be covered in the forthcoming sections are,
  • Target Annotation @Target: It specifies to which java elements annotation can be applied. Different java elements to which annotations can be applied are

1.    FIELD :can be applied only to Java Fields

2.    METHOD: can be applied only to methods.

3.    PARAMETER : can be applied only  to method parameters

4.    CONSTRUCTOR: can be applied only to constructor.

5.    LOCAL_VARIABLE : can be appliedonly  to Local variable

6.    TYPE: can be applied to java Type. e.g. It can be applied to Classes,interfaces,Enum .

7.    ANNOTATION_TYPE: can be applied only to Annotation Types.

8.    PACKAGE: can be applied to a Package.

  • Retention Annotation @Retention :This meta annotation specifies till what time annotations can be retained and when they can be discarded

1.    SOURCE :Retain annotation in source file and discard them at compile time

2.    CLASS : Retain annotation in class file and discard them at run time

3.    RUNTIME : Retain annotation at runtime and never discard them



How annotations are retrieved or read?
Annoations onece defined and used in some class we can read them using reflection package methods like getAnnotations().We have to first obtain the refrence to the class which contains or uses the Annotaions then we cane write code like given below
Class classObj = MyAnnotedClass.class;
Annotation[] annotations = classObj.getAnnotations();
for (Annotation annotation : annotations) {
 }


No comments:

Post a Comment