2014-11-04 19 views
-1

所以我試圖爲一個參數類創建一個代理。如何創建一個作爲參數給出的類的代理

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; 
} 

但是這不起作用的原因。這有什麼問題?

+0

有什麼錯誤? – 2014-11-04 09:30:04

+0

「cl不能解析爲類型」 – user2443088 2014-11-04 09:33:42

回答

1

cl是參數的名稱,而不是類型。

我猜.newProxyInstance()方法具有Proxy(或Object)返回類型,所以你只需要做:

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

好吧,這種回答我的問題。它工作時,我沒有 對象代理= Proxy.newProxyInstance(cl.class.getClassLoader(), 新類[] {CL}, 處理程序); – user2443088 2014-11-04 09:45:55

+0

這是可能的,是的。正如我告訴過你的,你需要檢查'newProxyInstance'方法的返回類型,它似乎是'Object'。 :) – 2014-11-04 09:58:24

相關問題