Rozważmy następujący kod:Jak sprawdzić, czy parametr obecnej metody ma adnotację i pobrać tę wartość parametru w Javie?
public example(String s, int i, @Foo Bar bar) {
/* ... */
}
Chcę sprawdzić, czy metoda ma adnotację @Foo
i uzyskać argumentu lub wyjątek, jeśli nie @Foo
adnotacja znajduje.
Moje obecne podejście jest, aby najpierw uzyskać aktualny sposób, a następnie iterację adnotacji parametrów:
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) {
/* ... */
}
}
}
}
Czy to właściwe podejście, czy jest jakiś lepszy? Jak wyglądałby kod wewnątrz pętli forach? Nie jestem pewien, czy zrozumiałem, co faktycznie powraca getParameterAnnotations
...
nie widzę nic złego masz już – skaffman
+1 nie robi 'new Exception(). getStackTrace()' – Cephalopod