拦截器
拦截器是我们开发中接触比较多的。今天使用JDK动态代理模式来实现拦截器。实现过程我们通过代码来展示,代码中有相应的解释:
//拦截器接口
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();
}
}