Host.java
package cn.zys.dynamiproxy; public class Host implements Rent{ public void rent(){ System.out.println("host房屋出租"); } @Override public void oks() { // TODO Auto-generated method stub System.out.println("我是最新的增强方法"); } }
Rent.java
package cn.zys.dynamiproxy; public interface Rent { public void rent(); public void oks(); }
ProxyInvocationHandler.java 实现InvocationHandler接口
package cn.zys.dynamiproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyInvocationHandler implements InvocationHandler{ private Object objs; public Object getObjs() { return objs; } public void setObjs(Object objs) { this.objs = objs; } /* * 生成代理类 * Loader 定义代理类的加载器 * Interfaces 定义代理类要实现接口的列表 * */ public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(), objs.getClass().getInterfaces(), this); } /* * proxy 是代理类 * method 代理类的调用处理程序的方法对象 * */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub log(method.getName()); Object obj = method.invoke(objs, args); return obj; } //看房 private void seehouse(){ System.out.println("看房"); } //收中介费 private void frea(){ System.out.println("收取中介费"); } //测试日志 public void log(String methodName){ System.out.println("执行"+methodName+"方法"); } }
实现类 Men.java
package cn.zys.dynamiproxy; import java.util.ArrayList; import java.util.List; public class Men { public static void main(String[] args) { // Host host = new Host(); // ProxyInvocationHandler pih = new ProxyInvocationHandler(); // pih.setObjs(host); // Rent rent = (Rent) pih.getProxy(); // rent.rent(); //测试list ProxyInvocationHandler pih = new ProxyInvocationHandler(); pih.setObjs(new ArrayList()); List list = (List) pih.getProxy(); list.add("haha"); } }
一个动态代理指某一个业务
一个动态代理可以代理多个类