今天在實現一個簡單的動態代理的時候莫名其妙出現了這樣一個報錯
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to org.cn.implment.LoginImplment
at org.cn.test.test.main(test.java:14)
源代碼
package org.cn.test;
import java.lang.reflect.Proxy;
import org.cn.Proxy.MyInvocationHandler;
import org.cn.implment.LoginImplment;
import org.cn.implment.loginInterface;
public class test {
public static void main(String[] args) {
LoginImplment loginTemp=new LoginImplment();
MyInvocationHandler mInvocationHandler=new MyInvocationHandler(loginTemp);
LoginImplment login=(LoginImplment) Proxy.newProxyInstance(loginTemp.getClass().getClassLoader(),
loginTemp.getClass().getInterfaces(), mInvocationHandler);
login.Login();
}
}
這裏面LoginImplment loginTemp
LoginImplment 是一個接口實現類,接口是loginInterface
還有MyInvocationHandler
是InvocationHandler
接口的實現類
MyInvocationHandler源碼:
package org.cn.Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler{
private Object obj;
public MyInvocationHandler() {
// TODO Auto-generated constructor stub
}
public MyInvocationHandler(Object obj) {
this.obj=obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("過濾");
Object reluset=method.invoke(this.obj, args);
System.out.println("登錄結束");
return reluset;
}
}
代碼大概看起來是沒問題,但就是報錯,最後查看文檔發現
看完後才猛然驚覺
改後代碼:
package org.cn.test;
import java.lang.reflect.Proxy;
import org.cn.Proxy.MyInvocationHandler;
import org.cn.implment.LoginImplment;
import org.cn.implment.loginInterface;
public class test {
public static void main(String[] args) {
LoginImplment loginTemp=new LoginImplment();
MyInvocationHandler mInvocationHandler=new MyInvocationHandler(loginTemp);
//注意這一塊是關鍵,要用實現類所實現的那個接口,而不是直接用實現類
loginInterface login=(loginInterface) Proxy.newProxyInstance(loginTemp.getClass().getClassLoader(),
loginTemp.getClass().getInterfaces(), mInvocationHandler);
login.Login();
}
}
Proxy.newProxyInstance返回的是實現類所實現的那個接口,而不是這個實現類,所以改正過後就沒有什麼問題了