Saturday 16 August 2014

Accessing Field Annotations

You can access the annotations of a class, method field or parameter at runtime. Here is an example that accesses the Field annotations.

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Test { 
    String name();
    String value();
}

public class TestClass {
    @Test(name="name", value="Name Of the person")
    public String name;
}

import java.lang.reflect.*;
import java.lang.annotation.*;

public class GetAnnotations {
    public static void main(String args[]) throws NoSuchFieldException{
        Class MyClass = TestClass.class;
        Field method = MyClass.getDeclaredField("name");
        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: name
value: Name Of the person





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment