JDK Proxy
//创建一个实例对象,这个对象是被代理的对象 Person zhangsan = new Student("张三"); //创建一个与代理对象相关联的InvocationHandler InvocationHandler stuHandler = new StuInvocationHandler<Person>(zhangsan); //创建一个代理对象stuProxy来代理zhangsan,代理对象的每个执行方法都会替换执行Invocation中的invoke方法 Person stuProxy = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(), new Class<?>[]{Person.class}, stuHandler); //代理执行上交班费的方法 stuProxy.giveMoney();
package proxy; /** * 创建Person接口 * @author Gonjan */ public interface Person { //上交班费 void giveMoney(); }
package proxy; public class Student implements Person{ private String name; public Student(String name) { this.name = name; } @Override public void giveMoney() { try { //假设数钱花了一秒时间 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + "上交班费50元"); } }
package proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class StuInvocationHandler<T> implements InvocationHandler { //invocationHandler持有的被代理对象 T target; public StuInvocationHandler(T target) { this.target = target; } /** * proxy:代表动态代理对象 * method:代表正在执行的方法 * args:代表调用目标方法时传入的实参 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("代理执行" +method.getName() + "方法"); //代理过程中插入监测方法,计算该方法耗时 MonitorUtil.start(); Object result = method.invoke(target, args); MonitorUtil.finish(method.getName()); return result; } }