views:

45

answers:

1

Suppose I have a function

public int doSomething(@QueryParam("id") String name, int x){ .... }

How can I find the type of the annotated parameter 'name'. I have a handle to the java.lang.reflect.Method instance of the function doSomething and using the function getParameterAnnotations(), I can obtain the annotation @QueryParam but am not able to access the parameter on which it is applied on. How do I do this ?

+2  A: 
void doSomething(@WebParam(name="paramName") int param) {  }

Method method = Test.class.getDeclaredMethod("doSomething", int.class);
Annotation[][] annotations = method.getParameterAnnotations();

for (int i = 0; i < annotations.length; i ++) {
    for (Annotation annotation : annotations[i]) {
        System.out.println(annotation);
    }
}

This outputs:

@javax.jws.WebParam(targetNamespace=, partName=, name=paramName, 
     header=false, mode=IN)

To explain - the array is two dimensional because first you have an array of parameters, and then for each parameter you have an array of annotations.

You can verify the type of the annotation you expect with instanceof (or Class.isAssignableFrom(..).

Bozho