java拦截器-基于JDK动态代理实现

(接上一篇的JDK动态代理,续讲拦截器生成原理)

 

自定义拦截器接口:IMyInterceptor.java

public interface IMyInterceptor {
    boolean before(Object proxy, Object target, Method method, Object[] args);  // 返回true时执行反射真实对象的方法;返回false执行around()方法

    int around(Object proxy, Object target, Method method, Object[] args);

    void after(Object proxy, Object target, Method method, Object[] args);
}

 

自定义拦截器类(实现接口):MyInterceptor.java

public class MyInterceptor implements IMyInterceptor {
    @Override
    public boolean before(Object proxy, Object target, Method method, Object[] args) {
        System.out.println("反射方法前逻辑");
        return false;
    }

    @Override
    public int around(Object proxy, Object target, Method method, Object[] args) {
        System.out.println("取代了反射方法");
        return 1;
    }

    @Override
    public void after(Object proxy, Object target, Method method, Object[] args) {
        System.out.println("反射方法后逻辑");
    }
}

 

使用JDK动态代理实现的拦截器:InterceptorJdkProxy.java(implements InvocationHandler)

public class InterceptorJdkProxy implements InvocationHandler {
    private Object target;
    private String interceptorClass = null;  // 拦截器全限定名

    public InterceptorJdkProxy(Object target, String interceptorClass) {
        this.target = target;
        this.interceptorClass = interceptorClass;
    }


    /**
     * 绑定真实对象和代理对象
     *
     * @param target
     * @param interceptorClass
     * @return
     */
    public static Object bind(Object target, String interceptorClass) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InterceptorJdkProxy(target, interceptorClass));
    }


    /**
     * 通过代理对象调用方法
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (interceptorClass == null) {
            return method.invoke(target, args);  // 直接反射原有方法
        }

        Object result = null;
        MyInterceptor interceptor = (MyInterceptor) Class.forName(interceptorClass).newInstance();  // 通过反射方式生成拦截器对象
        if (interceptor.before(proxy, target, method, args)) {
            result = method.invoke(target, args);
        } else {
            result = interceptor.around(proxy, target, method, args);
        }
        interceptor.after(proxy, target, method, args);
        return result;
    }
}

 

测试查看效果:TestInterceptor.java

public class TestInterceptor {
    public static void main(String[] args) {
        HelloWorld proxy = (HelloWorld) InterceptorJdkProxy.bind(new HelloWorldImpl(), "com.ssm.dynamicProxy.MyInterceptor");
        proxy.sayHello();
    }
}

 

输出:

反射方法前逻辑
取代了反射方法
反射方法后逻辑

 

posted @ 2023-11-07 10:47  DoubleFishes  阅读(106)  评论(0编辑  收藏  举报