前言
在Java動態(tài)代理中有兩個重要的類(接口)控嗜,一個是InvocationHandler(接口)讲冠,另外一個是Proxy(類)。這兩個類(接口)是實現(xiàn)動態(tài)代理不可或缺的。
組件介紹
1、InvocationHandler譬猫。這個接口有唯一一個方法invoke()。
Object invoke(Object proxy,Method method,Object[] args);
method:指代被調用的被代理對象的方法羡疗;
args:代用方法的時接受的參數(shù)染服;
2、Proxy顺囊。代理類的對象就是由該類中newProxyInstance()方法生成肌索。
pubblic static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,InvocationHandler h) throws IllegalArgumentException
loader:一個ClassLoader對象,定義由哪個
ClassLoader對象來對生成的代理類進行加載特碳。
interfaces:制定代理類要實現(xiàn)的接口诚亚。
h:動態(tài)代理對象調用方法時候會被關聯(lián)在一個
InvocationHandler對象上
代碼實例
被代理的類ComputeImpl實現(xiàn)Compute接口中的方法
public interface Compute {
int add(int x,int y);
}
public class ComputeImpl implements Compute {
@Override
public int add(int x, int y) {
System.out.println("add.....");
return x + y;
}
}
在實現(xiàn)代理的時候總結了以下兩種書寫的方法:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
public class Handler implements InvocationHandler {
private Object target;
public Handler(Object target){
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName() + "begin with " + Arrays.asList(args));
Object res = method.invoke(target,args);
System.out.println(method.getName() + "end with " + res);
return res;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class TestProxy {
public static void main(String[] args) {
Compute compute = new ComputeImpl();
//方法一
//額外定義一個Handler對象,將其和newInstance()關聯(lián)起來
Handler h = new Handler(compute);
Compute proxy1 = (Compute) Proxy.newProxyInstance(compute.getClass().getClassLoader(),
compute.getClass().getInterfaces(), h);
//方法二
//使用匿名內部類的方法
Compute proxy2 = (Compute)Proxy.newProxyInstance(compute.getClass().getClassLoader(),
compute.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName() + "begin with " + Arrays.asList(args));
Object res = method.invoke(compute,args);
System.out.println(method.getName() + "end with " + res);
return 10;
}
});
int res1 = proxy1.add(4,4);
System.out.println(res1);
int res2 = proxy2.add(8,8);
System.out.println(res2);
}
}