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 ?

1 Answer 1

2
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(..).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.