Como verificar se um parâmetro do método atual possui uma anotação e recuperar esse valor em Jav
Considere este código:
public example(String s, int i, @Foo Bar bar) {
/* ... */
}
Quero verificar se o método tem uma anotação@Foo
e obtenha o argumento ou lance uma exceção se não houver@Foo
anotação encontrada.
Minha abordagem atual é primeiro obter o método atual e, em seguida, percorrer as anotações de parâmetro:
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) {
/* ... */
}
}
}
}
Essa é a abordagem correta ou existe uma melhor? Como seria o código dentro do loop forach? Não sei se entendi o quegetParameterAnnotations
realmente retorna ...