【发布时间】:2011-11-05 21:56:57
【问题描述】:
考虑这段代码:
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 实际返回的内容...
【问题讨论】:
-
我没看出你有什么问题
-
+1 不做
new Exception().getStackTrace()
标签: java class reflection methods annotations