You
can access the annotations of a class, method field or parameter at
runtime. Here is an example that accesses the Method annotations.
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Test { String name(); String value(); }
public class TestClass { @Test(name="print", value="Print Data") public void print(){ } @Test(name="display", value="Display Data") public void display(){ } }
import java.lang.reflect.*; import java.lang.annotation.*; public class GetAnnotations { public static void main(String args[]) throws NoSuchMethodException{ Class MyClass = TestClass.class; Method method = MyClass.getDeclaredMethod("display"); Annotation ann[] = method.getAnnotations(); for(Annotation annotation : ann){ if(annotation instanceof Test){ Test myAnnotation = (Test) annotation; System.out.println("name: " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); } } } }
Output
name: display value: Display Data
No comments:
Post a Comment