Saturday, 16 August 2014

Accessing class Annotations

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

import java.lang.annotation.*;

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

@Test(name="sample", value="test")
public class TestClass {
    
}

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

public class GetAnnotations {
    public static void main(String args[]){
        Class aClass = TestClass.class;
        Annotation[] annotations = aClass.getAnnotations();

        for(Annotation annotation : annotations){
            if(annotation instanceof Test){
                Test myAnnotation = (Test) annotation;
                System.out.println("name: " + myAnnotation.name());
                System.out.println("value: " + myAnnotation.value());
            }
        }
    }
}

Output
name: sample
value: test


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment