前言
在Java动态代理中有两个重要的类(接口),一个是InvocationHandler(接口),另外一个是Proxy(类)。这两个类(接口)是实现动态代理不可或缺的。
组件介绍
1、InvocationHandler。这个接口有唯一一个方法invoke()。
Object invoke(Object proxy,Method method,Object[] args);
method:指代被调用的被代理对象的方法;
args:代用方法的时接受的参数;
2、Proxy。代理类的对象就是由该类中newProxyInstance()方法生成。
pubblic static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,InvocationHandler h) throws IllegalArgumentException
loader:一个ClassLoader对象,定义由哪个
ClassLoader对象来对生成的代理类进行加载。
interfaces:制定代理类要实现的接口。
h:动态代理对象调用方法时候会被关联在一个
InvocationHandler对象上
代码实例
被代理的类ComputeImpl实现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;
}
}
在实现代理的时候总结了以下两种书写的方法:
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()关联起来
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);
}
}