常用代码总结(动态代理)

常用代码总结(动态代理)

1. 基于 Java SDK
public class SimpleProxyByJavaSdk {
    interface Life {
        void work();
    }

    static class Person implements Life {
        public void work() {
            System.out.println("work hard!!!");
        }
    }

    static class SimpleInvocationHandler implements InvocationHandler {

        /**
         * 实际对象(被代理的对象)
         */
        private Object object;

        public SimpleInvocationHandler(Object object) {
            this.object = object;
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println(">>>>>> 实际方法调用之前");
            Object result = method.invoke(object, args);
            System.out.println(">>>>>> 实际方法调用之后");
            return result;
        }
    }

    /**
     * 获取代理类
     *
     * @param cls
     * @param object
     * @param <E>
     * @return
     */
    public static <E> E getProxy(Class<E> cls, E object) {
        E proxyInstance =
            (E)Proxy.newProxyInstance(cls.getClassLoader(), new Class<?>[] {cls}, new SimpleInvocationHandler(object));
        return proxyInstance;
    }

    public static void main(String[] args) {
        //创建实际对象
        Life life = new Person();
        //创建代理对象
        // Life proxyInstance = (Life)Proxy
        //     .newProxyInstance(Life.class.getClassLoader(), new Class<?>[] {Life.class}, new PersonInvokeHandler(life));
        Life proxyInstance = getProxy(Life.class, life);
        proxyInstance.work();
    }
}
2. 基于 cglib
public class SimpleProxyByCglib {
    static class Person {
        public void work() {
            System.out.println("work hard!!!");
        }
    }

    static class SimpleIntercaptor implements MethodInterceptor {
        /**
         * @param o           代理对象
         * @param method      真实行为
         * @param objects     参数列表
         * @param methodProxy 行为的代理
         * @return
         * @throws Throwable
         */
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println(">>>>>> 实际方法调用之前");
            Object result = methodProxy.invokeSuper(o, objects);
            System.out.println(">>>>>> 实际方法调用之后");
            return result;
        }
    }

    public static <E> E getProxy(Class<E> cls) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(cls);
        enhancer.setCallback(new SimpleIntercaptor());
        E proxy = (E)enhancer.create();
        return proxy;
    }

    public static void main(String[] args) {
        // Enhancer enhancer = new Enhancer();
        // enhancer.setSuperclass(Person.class);
        // enhancer.setCallback(new SimpleIntercaptor());
        // Person proxy = (Person)enhancer.create();
        Person proxy = getProxy(Person.class);
        proxy.work();
    }
}
posted @ 2020-12-20 02:44  东街浊酒づ  阅读(129)  评论(0编辑  收藏  举报