Tuesday, February 12, 2013

Annotation concept in JAVA

Annotation is a concept introduced by J2SE 5 and above it that allows programmers to add additional information called metadata into a Java source file. Annotations do not change the execution of a program but the information embedded using annotations can be used by various tools during development and deployment.


Annotation is similar to creating an interface. Having declaration preceded by an @ symbol. The @Retention annotation is used to specify the retention policy, i.e. SOURCE, CLASS, or RUNTIME.

RetentionPolicy.SOURCE retains an annotation only in the source file and discards it during compilation.
RetentionPolicy.CLASS stores the annotation in the .class file but does not make it available during runtime.
RetentionPolicy.RUNTIME stores the annotation in the .class file and also makes it available during runtime.


There are two part for Annotation

1) Annotation Type
2) Annotation itself


1) Annotation Type

package hello;

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

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String MyAuthor();    // Annotation member
    String MyDate();      // Annotation member
}

2) Annotation itself

package hello;

import java.lang.reflect.Method;

@MyAnnotation(MyAuthor="Siddhu",MyDate="12/2/2013,12/02/2013")
public class TestMyAnnotation {
@MyAnnotation(MyAuthor="Siddhu",MyDate="12/02/2013")
   public static void myMethod()
   {
       System.out.println("Hi .......... inside the method");      
   }
public static void showMyAnnotations()
{
TestMyAnnotation test=new TestMyAnnotation();
   try
   {
    Class c=test.getClass();
       Method m=c.getMethod("myMethod");
       MyAnnotation annotation1=(MyAnnotation)c.getAnnotation(MyAnnotation.class);
       MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class);
       System.out.println("Author for class: "+annotation1.MyAuthor());
       System.out.println("Date for  class: "+annotation1.MyDate());
       System.out.println("Author for method: "+annotation2.MyAuthor());
       System.out.println("Date for method: "+annotation2.MyDate());
   }
   catch(NoSuchMethodException ex)
   {
       System.out.println("Invalid Method..."+ex.getMessage());
   }
}
   public static void main(String args[])
   {
       myMethod();
       showMyAnnotations();
   }
}


OutPut:

Hi .......... inside the method
Author of the class: Siddhu
Date of Writing the class: 12/2/2013,12/02/2013
Author of the method: Siddhu
Date of Writing the method: 12/02/2013

No comments: