1.創(chuàng)建接口:
/** * @author JingZhe @time 2021/10/20 9:45 */ public interface Person { /** 測試方法 */ void doSomething(); }
2.創(chuàng)建接口的實現(xiàn)類:
/** * @author JingZhe @time 2021/10/20 9:48 */ public class JingZhe implements Person { @Override public void doSomething() { System.out.println("jingZhe doing Something"); } }
3.創(chuàng)建動態(tài)代理類:
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * @author JingZhe @time 2021/10/20 9:44 */ public class JDKDynamicProxy implements InvocationHandler { /** 聲明被代理的對象 */ private Person person; /** 構(gòu)造函數(shù) */ public JDKDynamicProxy(Person person) { this.person = person; } /** 獲取代理對象 */ public Object getProxy() { Object proxyInstance = Proxy.newProxyInstance(person.getClass().getClassLoader(), person.getClass().getInterfaces(), this); return proxyInstance; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("對原方法進行了前置增強"); // 原方法執(zhí)行 Object invoke = method.invoke(person, args); System.out.println("對原方法進行了后置增強"); return invoke; } }
4.編寫測試類:
/** * @author JingZhe @time 2021/10/20 9:46 */ public class proxyTest { public static void main(String[] args) { System.out.println("不使用代理類,調(diào)用doSomething"); Person person = new JingZhe(); person.doSomething(); System.out.println("--------------------------"); System.out.println("使用代理類,調(diào)用doSomething"); Person proxy = (Person) new JDKDynamicProxy(new JingZhe()).getProxy(); proxy.doSomething(); } }
測試結(jié)果:
不使用代理類,調(diào)用doSomething jingZhe doing Something -------------------------- 使用代理類,調(diào)用doSomething 對原方法進行了前置增強 jingZhe doing Something 對原方法進行了后置增強
以上。
本文摘自 :https://www.cnblogs.com/