动态代理简单实现
1.以小芳找对象为例子,需要媒婆这个代理类。
public class XiaoFang implements Girl {
@Override
public void SearchObject() {
System.out.println("我是小芳,我想找对象。");
}
}
2.此处根据jdk规定,被代理的类必须实现一个接口。
public interface Girl {
void SearchObject();
}
3.媒婆代理类的实现
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*
* 媒婆类,代理小芳的找对象需求。
*/
public class MeiPo implements InvocationHandler {
//需要代理的对象
private Object object;
public MeiPo(Object object) {
this.object=object;
}
public Object getObject() {
/*
* 参数解释:
* loader: the class loader to define the proxy class(定义代理类的类加载器)
* interfaces:the list of interfaces for the proxy classto implement(要实现的代理类的接口列表)
* h: the invocation handler to dispatch method invocations to(要将方法调用分派到的调用处理程序)
*/
return Proxy.newProxyInstance(this.getClass().getClassLoader(), this.object.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//此处为增强代码
System.out.println("打开链接");
Object invoke = method.invoke(this.object, args);
System.out.println("结束链接");
//增强代码
return invoke;
}
}
关键点就在newProxyInstance的三个参数的理解。
4.测试类实现
public class Xiaowang {
public static void main(String[] args) {
XiaoFang xiaofang=new XiaoFang();
MeiPo meiPo=new MeiPo(xiaofang);
Girl girl = (Girl)meiPo.getObject();
girl.SearchObject();
}
}
简单动态代理实现就此结束。