三种实现动态代理方式(jdk、cglib、javaassist)

在编写程序与实现某些功能时,我们经常会使用到动态代理。动态代理是个很简单但是很有效的东西。在我们平时使用的框架中,像servlet的filter、包括spring提供的aop以及struts2的拦截器都使用了动态代理功能。我们日常看到的mybatis分页插件,以及日志拦截、事务拦截、权限拦截这些几乎全部由动态代理的身影。它的实现原理是非常简单的,就是在方法实现前后加入对应的公共功能,下面我写了以下三种方式的实现
package com.jfinal.template;

import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by TT on 2018-02-05.
 */
public class CglibTest {

    @Test
    public void test() throws Exception {
        //jdk
        //缺点 必须有接口
        //优点 简单
        T1 t1 = (T1)Proxy.newProxyInstance(T1_00.class.getClassLoader(), T1_00.class.getInterfaces(), new T1_01(new T1_00()));
        t1.say();

        //cglib
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(T2.class);
        enhancer.setCallback(new T2_01(new T2()));
        T2 t2 = (T2)enhancer.create();
        t2.say();

        //javaassist
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setSuperclass(T3.class);
        proxyFactory.setHandler(new T3_01(new T3()));
        T3 t3 = (T3)proxyFactory.createClass().newInstance();
        t3.say();
    }
}


class T3 {
    public void say() {
        System.out.println("ccc");
    }
}

class T3_01 implements MethodHandler {
    private T3 t3;

    public T3_01(T3 t3) {
        this.t3 = t3;
    }

    @Override
    public Object invoke(Object o, Method method, Method method1, Object[] objects) throws Throwable {
        System.out.println("ccc before");
        method.invoke(new T3(), objects);
        System.out.println("ccc after");
        return o;
    }
}

class T2 {
    public void say() {
        System.out.println("bbb");
    }
}

class T2_01 implements MethodInterceptor {
    private T2 t2;

    public T2_01(T2 t2) {
        this.t2 = t2;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("before day");
        method.invoke(t2, objects);
        System.out.println("before after");
        return o;
    }
}

interface T1 {
    void say();
}

class T1_00 implements T1{
    @Override
    public void say() {
        System.out.println("aaa");
    }
}

class T1_01 implements InvocationHandler {
    private T1_00 t1_00 = null;

    public T1_01(T1_00 t1_00) {
        this.t1_00 = t1_00;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        method.invoke(t1_00, args);
        System.out.println("after");
        return proxy;
    }
}
阅读更多
个人分类: java
上一篇java中break用法
下一篇使用fastjson实现field首字母大写
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭