Wednesday, January 21, 2009

Sample Annotation

A Novice Program for writing own Annotation. Annotations are not rocket science, they just have retention policy (runtime, source, class) and target (field, method, class, type, parameter) and finally can be looked using Reflection API.

MyAnnotation.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)

@Target(value = { ElementType.FIELD })

public abstract @interface MyAnnotation {
boolean enabled() default true;
String input() default "";
String output() default "";
int value() default -1;

}

Usage.java
import java.lang.reflect.Field;
public class Usage {
@MyAnnotation(input = "Hello")

public int a;
public void myMethod() {

Class<? extends Usage> c = this.getClass(); Field f = null;
try {
f = c.getField("a");
} catch (SecurityException e) { e.printStackTrace();
} catch (NoSuchFieldException e) { e.printStackTrace();
}
MyAnnotation ma = (MyAnnotation) f.getAnnotation(MyAnnotation.class);
System.out.println(ma.input());
}
public static void main(String args[]) {

Usage u = new Usage(); u.myMethod(); }
}

No comments: