1、依赖
java.lang.reflect.Proxy - 提供了静态方法去创建动态代理类的实例;
Interface InvocationHandler - 一个代理实例调用处理程序实现的接口
2、编写代理实例处理类
public class InvocationHandlerProxy implements InvocationHandler { //被代理的接口 private Object target; //获取代理角色 public void setTarget(Object target){ this.target = target; } //获得一个代理类 public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } //处理代理实例,并返回结果 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log(); Object o = method.invoke(this.target, args); return o; } private void log(){ System.out.println("执行前日志"); } }
3、测试
//真实角色-被代理对象 Landlord landlord = new Landlord(); //实例化代理实例类 InvocationHandlerProxy handlerProxy = new InvocationHandlerProxy(); //设置要代理的对象 handlerProxy.setTarget(landlord); //生成代理类InvocationHandlerProxy,以被代理对象的接口强转 Sent proxy = (Sent) handlerProxy.getProxy(); //代理真实操作 proxy.rest();