Consider this code:
public example(String s, int i, @Foo Bar bar) {
/* ... */
}
I want to check if the method has an annotation @Foo
The outer for loop
for (Annotation[] annotations : paramAnnotations) {
...
}
should use an explicit counter, otherwise you don't know what parameter you are processing right now
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
final Class[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramAnnotations.length; i++) {
for (Annotation a: paramAnnotations[i]) {
if (a instanceof Foo) {
System.out.println(String.format("parameter %d with type %s is annotated with @Foo", i, paramTypes[i]);
}
}
}
Also make sure your annotation type is annotated with @Retention(RetentionPolicy.RUNTIME)
From your question it is not entirely clear what you are trying to do. We agree on the difference of formal parameters vs. actual arguments:
void foo(int x) { }
{ foo(3); }
where x
is a parameter and 3
is an argument?
It is not possible to get the arguments of methods via reflection. If it is possible at all, you would have to use the sun.unsafe
package. I can't tell you much about that though.