在读取代理类方法的注释时遇到问题。
在方法上有一个接口,一个对象和一个注释,这部分非常简单:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface A {
}
interface I {
void method();
}
class Test implements I {
@A
public void method() { }
}
接下来,有一个invocationHandler
什么也不做,只是简单地调用带有传递参数的方法:
class DefaultinvocationHandler implements invocationHandler {
@Override
public Object invoke(final Object o,final Method method,final Object[] args) throws Throwable {
return method.invoke(o,args);
}
}
有一个main
方法可以打印Test
实例及其代理对应对象的声明方法:
class Main {
public static void main(String[] args) {
Object test = new Test();
printMethods(test); // Outputs that `I#method` has `A` annotation
System.out.println();
Object proxied = Proxy.newProxyInstance(test.getclass().getclassLoader(),test.getclass().getInterfaces(),new DefaultinvocationHandler());
printMethods(proxied); // Outputs that `I#method` does not have `A` annotation
}
static void printMethods(Object obj) {
Arrays.stream(obj.getclass().getDeclaredMethods())
.forEach(method -> System.out.println(method.toString() + " has A annotation: " + method.isAnnotationPresent(A.class)));
}
}
问题就来了:局部变量test
是Test
类的实例,而局部变量proxied
实际上是Proxy
,所以它没有其方法上的任何注释。这是程序的输出:
public void Test.method() has A annotation: true // <- good thing
public final boolean $Proxy2.equals(java.lang.Object) has A annotation: false
public final java.lang.String $Proxy2.toString() has A annotation: false
public final void $Proxy2.method() has A annotation: false // <- bad thing
public final int $Proxy2.hashCode() has A annotation: false
我尝试搜索解决方案,但是this question涉及从注释中提取注释(我想),this one也是关于注释类的。 Some of them与其他代理实现有关。
➥那么,是否有任何方法可以从代理对象中获取实际的注释,或者公开隐藏在代理下的类(不过,我想要前一个)?