Tuesday, April 08, 2014

Java Annotations by Example


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

/**
 * Annotations are defined via the @interface annotation before the class name.
 * Via @Retention you define if the annotation should be retained at runtime or
 * not. The @Target annotation lets you define where this annotation can be
 * used, e.g. the class, fields, methods, etc.
 * 
 * @author Watsh
 * 
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CanRun {

}
public class AnnotatedMethodsClass {

    public void method1() {
        System.out.println("method1");
    }

    @CanRun
    public void method2() {
        System.out.println("method2");
    }

    @CanRun
    public void method3() {
        System.out.println("method3");
    }

    public void method4() {
        System.out.println("method4");
    }

    public void method5() {
        System.out.println("method5");
    }

} 
import java.lang.reflect.Method;

public class AnnotationAnalyzer {

 /**
  * The main method of this class analyzes the annotations and calls the
  * corresponding methods.
  * 
  * @param args
  */
 public static void main(String[] args) {
  AnnotatedMethodsClass clz = new AnnotatedMethodsClass();
  Method[] methods = clz.getClass().getMethods();

  for (Method m : methods) {
   CanRun annos = m.getAnnotation(CanRun.class);
   if (annos != null) {
    try {
     m.invoke(clz);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
 }
}

No comments: