【发布时间】:2009-10-21 09:08:08
【问题描述】:
我正在寻找一种方法来提取 Java 中签名的本质。原因是我想在我的 java.lang.reflect.Proxies 的 Map 中使用签名作为唯一键。
使用此代码:
public interface MyInterface {
public int compute(String s);
}
...
public static void main (String... args) throws Exception {
InvocationHandler handler = ...;
MyInterface i = (MyInterface) Proxy.newProxyInstance(
Beans.class.getClassLoader(),
new Class<?>[] { MyInterface.class },
handler);
Method m1 = MyInterface.class.getMethod("compute", String.class);
Method m2 = i.getClass().getMethod("compute", String.class);
System.out.printf("%b%f", m1.equals(m2));
}
结果显然是假的。
此代码不是我将使用的代码,因为我需要在 InvocationHandler 中使用它,但我想知道关于代理实现和接口,获取 method.getName() 和 method.getParameterTypes() 是否足够或者我应该使用method.getTypeParameters() 和 method.getParameterAnnotations() 也一样?
简而言之:如何获得与接口及其 java.lang.reflect.Proxy 实现相同的方法签名?
【问题讨论】:
-
您需要将代理存储在地图中吗?创建它们并不昂贵,可能不值得缓存它们。
-
不,我不存储我的代理:只是方法,所以我避免了一个 loooooooong 开关。
-
我的意思是,为什么不在每次需要时创建代理,而不是通过方法签名查找它们?
标签: java reflection proxy method-signature