1、需要代理的类
package com.sgl.invocation; public class Vendor implements Sell{ @Override public void sell() { System.out.println("In sell method"); } @Override public void add() { System.out.println("add method"); } }
2、InvocationHandler
package com.sgl.invocation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicProxy implements InvocationHandler{ private Object object;//目标对象 public DynamicProxy(Object object) { super(); this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//proxy为代理类对象 System.out.println("before"); Object result = method.invoke(object, args); System.out.println("after"); return result; } /** * 根据目标对象生成代理对象 * @return */ public Object getProxy(){ return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), object.getClass().getInterfaces(), this); } }
3、测试类
package com.sgl.invocation; public class ProxyTest { public static void main(String[] args) { //实例化目标对象 Sell sell = new Vendor(); // 实例化InvocationHandler DynamicProxy invocationHandler = new DynamicProxy(sell); // 根据目标对象生成代理对象 Sell proxy = (Sell) invocationHandler.getProxy(); // 调用代理对象的方法 proxy.add(); } }
总结:现在只会用,底层原理暂时看不懂!