package cn.zr.proxy.dao; public interface PersonDao { public void eat(String name); }
package cn.zr.proxy.dao.impl; import cn.zr.proxy.dao.PersonDao; public class PersonDaoImpl implements PersonDao { public void eat(String name) { System.out.println(name+"吃饭"); } }
package cn.zr.proxy.dao.entity; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ProxyHandler implements InvocationHandler{ //要代理的对象 private Object proxyObject; public ProxyHandler() { } public ProxyHandler(Object proxyObject) { super(); this.proxyObject = proxyObject; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //在代理真实对象前进行操作 System.out.println("吃饭前,先洗手"); // 代理对象调用真实对象的方法 Object resultObj = method.invoke(proxyObject, args); //代理真实对象后进行操作 System.err.println("吃完饭后,记得洗碗"); return resultObj; } }
package cn.zr.proxy.dao.utils; import java.lang.reflect.Proxy; import cn.zr.proxy.dao.PersonDao; import cn.zr.proxy.dao.entity.ProxyHandler; import cn.zr.proxy.dao.impl.PersonDaoImpl; public class TestUtils { public static void main(String[] args) { //创建实现类 PersonDao personDao = new PersonDaoImpl(); //创建代理类,并把真实代理对象传进去 ProxyHandler proxyHandler = new ProxyHandler(personDao); //被代理的对象 PersonDao person = (PersonDao)Proxy.newProxyInstance(proxyHandler.getClass().getClassLoader(), personDao.getClass().getInterfaces(), proxyHandler); person.eat("人"); } }