Saturday 16 August 2014

Accessing Parameter 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.PARAMETER)
public @interface Test { 

}

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

public class GetAnnotations {
    public void testMethod(String noAnnotation,
        @Test String withAnnotation){
    }

    public static void main(String[] args) throws Exception {
        Class myClass = GetAnnotations.class;
        Method method = myClass.getDeclaredMethod("testMethod", String.class, String.class);
        Annotation[][] annotations = method.getParameterAnnotations();
        for (Annotation[] ann : annotations) {
            System.out.printf("%d annotatations", ann.length);
            System.out.println();
        }
    }
}

Output
0 annotatations
1 annotatations



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment