Consider this code:
public example(String s, int i, @Foo Bar bar) {
/* ... */
}
I want to check if the method has an annotation @Foo
and get the argument or throw an exception if no @Foo
annotation is found.
My current approach is to first get the current method and then iterate through the parameter annotations:
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
class Util {
private Method getCurrentMethod() {
try {
final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
final StackTraceElement ste = stes[stes.length - 1];
final String methodName = ste.getMethodName();
final String className = ste.getClassName();
final Class<?> currentClass = Class.forName(className);
return currentClass.getDeclaredMethod(methodName);
} catch (Exception cause) {
throw new UnsupportedOperationException(cause);
}
}
private Object getArgumentFromMethodWithAnnotation(Method method, Class<?> annotation) {
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : paramAnnotations) {
for (Annotation an : annotations) {
/* ... */
}
}
}
}
Is this the right approach or is there a better one?
How would the code inside the forach loop look like? I'm not sure if I have understood the what getParameterAnnotations
actually returns...
The isAnnotation() method is used to check whether a class object is an annotation. The isAnnotation() method has no parameters and returns a boolean value. If the return value is true , then the class object is an annotation.
Annotations are used to provide supplemental information about a program. Annotations start with '@'. Annotations do not change the action of a compiled program. Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With