考慮以下代碼:如何檢查當前方法的參數是否有註釋並在Java中檢索該參數值?
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
實際返回的內容...
我看不出有什麼錯,你已經 – skaffman
+1因爲沒有執行'new Exception()。getStackTrace()' – Cephalopod