In java internal interceptors are actually implemented by jdk dynamic proxy
Interceptor generally at least three ways: before, around, after, before and after the logic used to intercept method, specific logic is as follows:
1. Definition Interceptor:
/** * 定义拦截器接口 */ public interface Interceptor { public boolean before(Object proxy, Object target, Method method, Object[] args); public void around(Object proxy, Object target, Method method, Object[] args); public void after(Object proxy, Object target, Method method, Object[] args); } public class MyInterceptor implements Interceptor { @Override public boolean before(Object proxy, Object target, Method method, Object[] args) { System.err.println("反射方法前逻辑"); return to false ; } @Override public void around (Proxy Object, Object target, Method, Method, Object [] args) { System.err.println ( "a method is unsubstituted agent" ); } @Override public void After (Object Proxy , Object target, method, method, Object [] args) { System.err.println ( "logic after reflection method" ); } }
2. Use interceptors in JDK dynamic proxy
Define a dynamic proxy class, the compositions come interceptor, interceptor logic implemented invoke method
public class InterceptorJdkProxy implements InvocationHandler { private Object target; private String interceptorClass = null; //通过拦截器类名引入 public InterceptorJdkProxy(Object target, String interceptorClass) { this.interceptorClass = interceptorClass; this.target = target; } public static Object bind(Object target, String interceptorClass) { return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), newInterceptorJdkProxy (target, interceptorClass)); } @Override public Object Invoke (Object Proxy, Method, Method, Object [] args) throws the Throwable { // identification interceptor is not provided, can call the original method returns IF (interceptorClass == null ) { return Method.invoke (target, args); } Object Result = null ; // class name generated interceptor object reflector interceptor interceptor = (myInterceptor) the Class.forName (interceptorClass) .newInstance (); IF (interceptor.before (Proxy , target, Method, args)) { Result= method.invoke(target, args); } else { interceptor.around(proxy, target, method, args); } interceptor.after(proxy, target, method, args); return result; } }
Truly interceptor invoke methods in logic, it is called a variety of internal reflection
test:
public interface HelloWorld{ public void sayHelloWorld(); } class HelloWorldImp implements HelloWorld{ @Override public void sayHelloWorld(){ System.out.println("Hello World!"); } } // ------------------ public class InterceptorTest { public static void main(String[] args) { HelloWorld hwProxy = (HelloWorld) InterceptorJdkProxy.bind(new HelloWorldImp(), MyInterceptor.class.getName()); hwProxy.sayHelloWorld(); } }
Output:
The method of the front reflector logic
replaces the proxy method
after reflection method logic