關於JAVA動態代理出現ClassCastException異常的問題

今天在實現一個簡單的動態代理的時候莫名其妙出現了這樣一個報錯

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 loginTempLoginImplment 是一個接口實現類,接口是loginInterface還有MyInvocationHandlerInvocationHandler接口的實現類

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返回的是實現類所實現的那個接口,而不是這個實現類,所以改正過後就沒有什麼問題了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章