【问题标题】:How create a proxy for a class that is given as a parameter如何为作为参数给出的类创建代理
【发布时间】:2014-11-04 09:27:58
【问题描述】:

所以我正在尝试为作为参数的类创建代理。

public static Object lookup(Class<?> cl,
                            CommunicationModule communicationModule) {
    InvocationHandler handler = new InvocationHandler() { ... };
    cl proxy = (cl) Proxy.newProxyInstance(cl.class.getClassLoader(),
                                           new Class[] { cl.class }, handler);
    return proxy;
}

但这由于某种原因不起作用。这有什么问题?

【问题讨论】:

  • "cl 无法解析为类型"

标签: java generics proxy


【解决方案1】:

cl 是参数的名称,而不是类型。

我猜.newProxyInstance() 方法的返回类型为Proxy(或Object),所以你只需要这样做:

Object proxy = Proxy.newProxyInstance(cl.class.getClassLoader(),
                                     new Class[] { cl }, 
                                     handler);

【讨论】:

  • 好的,这样回答了我的问题。当我执行 Object proxy = Proxy.newProxyInstance(cl.class.getClassLoader(), new Class[] { cl }, handler);
  • 有可能,是的。正如我告诉你的,你需要检查newProxyInstance 方法的返回类型,它似乎是Object。 :)
猜你喜欢
  • 1970-01-01
  • 2018-11-13
  • 2020-10-05
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多