- 在java動態代理機制中有兩個很重要的接口,一個就是java.lang.reflect.InvocationHandler,另一個就是java.lang.reflect.Proxy。首先介紹下這兩個接口的作用和參數。
- 大概意思是每個動態代理類都要實現InvocationHandler接口,並且關聯到一個handler,通過代理對象調用時,這個接口的方法調用就會轉接到該handler的invoke方法進行調用。
- invoke方法
- proxy,該參數是代理的真實對象
- method,該參數是代理的方法
- 代理方法中接受的參數
- Proxy這個接口:
- 靜態 方法獲取代理對象
- 第一個參數是需要代理的對象的classloader
- 第二個參數是:需要代理對象的一組接口,代理之後,就可以調用這一組接口中的方法了
- 第三個參數:是InvocationHandler表示關聯到哪個Handler上
案例
- 定義需要被代理的接口
- 定義需要被代理的實現類
- 定義代理類,必須實現InvocationHandler接口
import java.lang.invoke.MethodHandleInfo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyInvocationHandler implements InvocationHandler {
private Object realObject;
private Object proxyObject;
public MyInvocationHandler(Object reObject) {
super();
this.realObject = reObject;
this.proxyObject = Proxy.newProxyInstance(realObject.getClass().getClassLoader(),
realObject.getClass().getInterfaces(), this);
}
public Object getProxyObject() {
return proxyObject;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("在代理方法之前執行了");
method.invoke(realObject, args);
System.out.println("在代理方法之後執行了");
return null;
}
}
import org.junit.Test;
public class ProxyTest {
@Test
public void test1() {
MyInterfaceImp myInterfaceImp = new MyInterfaceImp();
MyInvocationHandler handler = new MyInvocationHandler(myInterfaceImp);
MyInterface proxy = (MyInterface) handler.getProxyObject();
String say2 = proxy.say2();
System.out.println(say2);
}
}
- 結果: