soc*_*soc 10 java reflection methods annotations class
考虑以下代码:
public example(String s, int i, @Foo Bar bar) {
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
我想检查方法是否有注释@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) {
/* ... */
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方法还是有更好的方法?forach循环中的代码如何?我不确定我是否理解了getParameterAnnotations
实际返回的内容......
外部for循环
for (Annotation[] annotations : paramAnnotations) {
...
}
Run Code Online (Sandbox Code Playgroud)
应该使用显式计数器,否则你不知道你现在正在处理什么参数
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
final Class[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramAnnotations.length; i++) {
for (Annotation a: paramAnnotations[i]) {
if (a instanceof Foo) {
System.out.println(String.format("parameter %d with type %s is annotated with @Foo", i, paramTypes[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
还要确保注释类型带有注释 @Retention(RetentionPolicy.RUNTIME)
从你的问题来看,你想要做的事情并不完全清楚.我们同意形式参数与实际参数的区别:
void foo(int x) { }
{ foo(3); }
Run Code Online (Sandbox Code Playgroud)
x
参数在哪里,3
是一个参数?
通过反射得到方法的参数是不可能的.如果可能,您将不得不使用该sun.unsafe
包.虽然我不能告诉你太多.