АннотированныйЭлемент Javadoc
отрим этот код:
public example(String s, int i, @Foo Bar bar) {
/* ... */
}
Я хочу проверить, есть ли у метода аннотация@Foo
и получить аргумент или бросить исключение, если нет@Foo
аннотация найдена.
Мой текущий подход заключается в том, чтобы сначала получить текущий метод, а затем выполнить итерации по аннотациям параметров:
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) {
/* ... */
}
}
}
}
Это правильный подход или есть лучший? Как будет выглядеть код внутри цикла forach? Я не уверен, что понял, чтоgetParameterAnnotations
на самом деле возвращается ...