consideran este código:¿Cómo comprobar si un parámetro del método actual tiene una anotación y recuperar ese valor del parámetro en Java?
public example(String s, int i, @Foo Bar bar) {
/* ... */
}
Quiero comprobar si el método tiene una anotación @Foo
y obtener el argumento o una excepción si no se encuentra ninguna @Foo
anotación.
Mi enfoque actual es conseguir primero el método actual y luego iterar a través de las anotaciones de los parámetros:
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) {
/* ... */
}
}
}
}
Es este el enfoque correcto o hay una mejor? ¿Cómo se vería el código dentro del lazo del forjado? No estoy seguro de haber entendido lo que realmente devuelve getParameterAnnotations
...
no veo nada de malo en que ya tiene – skaffman
1 por no hacer 'new Exception(). getStackTrace()' – Cephalopod