Computing Magazine

Create Custom Annotation In Java

Posted on the 25 June 2013 by Abhishek Somani @somaniabhi
Annotations are meta data to be used by compiler or run time environment.Creating your custom annotation in java is very simple .
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
 String value() default "myAnootation";
 String[] arr() default {"testarr"};
}
Here , the RetentionPolicy.RUNTIME will determine whether the annotation will be present at run time or not.To test the annotation and get the values , let's create a test class
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 
 * 
 * @author Abhishek Somani
 * 
 */
public class MyAnnotationTest {
 
 @MyAnnotation(value="test my annotation",arr={"my arr test"})
 public void annotationTest()
 {
  
 }
 
 
 public static void main(String[] args) {
  Method[] methods = MyAnnotationTest.class.getDeclaredMethods();
  
  for(Method m : methods)
  {
   for(Annotation a : m.getAnnotations())
   {
    if ( a instanceof MyAnnotation)
    {
     MyAnnotation ann = (MyAnnotation)a;
     System.out.println(ann.value());
     for(String s : ann.arr())
     {
      System.out.println(s);
     }
    }
   }
  }
  
  
  
 }

}
Here annotation is on method level , we can access the annotation element values using reflection on method.If the do not specify RetentionPolicy as RUNTIME , the jvm will ignore this annotation and we will not be able to access this annotation. Create Custom Annotation In java Post Comments and Suggestions !!

Back to Featured Articles on Logo Paperblog

Magazines