攔截器是咱們開發中接觸比較多的。今天使用JDK動態代理模式來實現攔截器。實現過程咱們經過代碼來展現,代碼中有相應的解釋:ide
//攔截器接口 public interface Interceptor { /** * 調用真實方法以前執行,寫調用真實方法的前提邏輯 * @param proxy 代理對象 * @param obj 真實對象 * @param method 方法 * @param args 方法參數 * @return */ public boolean before(Object proxy,Object obj,Method method,Object[] args); /** * 當before方法結果是false時,調用此方法 * @param proxy * @param obj * @param method * @param args */ public void around(Object proxy,Object obj,Method method,Object[] args); /** * 調用完真實對象或者執行完around方法以後執行此方法 * @param proxy * @param obj * @param method * @param args */ public void after(Object proxy,Object obj,Method method,Object[] args); }
//攔截器實現類 public class InterceptorImpl implements Interceptor { @Override public boolean before(Object proxy, Object obj, Method method, Object[] args) { System.out.println("反射方法執行以前的邏輯~~"); return false; } @Override public void around(Object proxy, Object obj, Method method, Object[] args) { System.out.println("執行around方法~~~"); } @Override public void after(Object proxy, Object obj, Method method, Object[] args) { System.out.println("反射方法以後的邏輯~~"); } }
//JDK動態代理所須要的接口 public interface ISayHello { public void say(); }
//JDK動態代理接口實現類 public class SayHelloImpl implements ISayHello { @Override public void say() { System.out.println("真實對象邏輯~Hello World!"); } }
//jdk動態代理實現攔截器 public class InterceptorJdkProxy implements InvocationHandler { //真實對象 private Object obj; //攔截器權限定名 private String interceptorClass = null; public Object bind(Object obj,String interceptorClas) { this.obj = obj; this.interceptorClass = interceptorClas; Object proxy = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this); return proxy; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //若是沒有攔截器,直接走原邏輯 if(interceptorClass == null) { return method.invoke(obj, args); } //接收真實對象方法 Object result = null; //反射生成攔截器對象 Interceptor interceptor = (Interceptor) Class.forName(interceptorClass).newInstance(); if(interceptor.before(proxy, obj, method, args)) { result = method.invoke(obj, args); } else { interceptor.around(proxy, obj, method, args); } interceptor.after(proxy, obj, method, args); return result; } }
//測試代碼 public class TestInterceptor { public static void main(String[] args) { InterceptorJdkProxy interceptorJdkProxy = new InterceptorJdkProxy(); ISayHello bind = (ISayHello) interceptorJdkProxy.bind(new SayHelloImpl(), "interceptor.InterceptorImpl"); bind.say(); } }