CGlib 入门

CGlib 入门

cglib github地址链接

项目maven构建:

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.1</version>
</dependency>

项目gradle构建:

dependencies {
    compile 'cglib:cglib:3.1'
    testCompile 'junit:junit:4.11'
}

cglib不仅可以动态创建实现了接口类的代理对象,还可以为简单的POJO动态创建代理对象;而java只能动态创建实现了接口类的代理对象(使用Proxy类和InvocationHandler接口)。

1,Enhancer和FixedValue

cglib中最重要的就是net.sf.cglib.proxy.Enhancer这个类,与java中的Proxy类有异曲同工之妙,都可以创建代理对象。

下面就来简单实验一下:
首先新建一个简单的POJO类CGlibSample.java

public class CGlibSample {

    public String test(String input){
        return input;
    }
}

测试类TestCG.java:

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.FixedValue;
import org.junit.Assert;
import org.junit.Test;

public class TestCG {

    @Test
    public void testFixedValue() throws Exception {

        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(CGlibSample.class);

        /*enhancer.setCallback(new FixedValue() {
            @Override
            public Object loadObject() throws Exception {
                return "Hello cglib!";
            }
        });*/

        //java lambda expression 与上面的代码段效果一样
        enhancer.setCallback((FixedValue)() -> {
            return "Hello cglib!";
        });

        CGlibSample proxy = (CGlibSample)enhancer.create();

        Assert.assertEquals("Hello cglib!",proxy.test("hello!"));
        Assert.assertEquals("Hello cglib!",proxy.toString());
        Assert.assertFalse("hello!".equals
        (proxy.test("hello!")));    

    }
}

这里的FixedValue接口相当于一个拦截器(interceptor)。
proxy.getClass()
输出结果为 class glib.CGlibSample$$EnhancerByCGLIB$$c9fa3aa1,明显可以看这是个有cglib产生的代理对象,目标对象为glib.CGlibSample
由以上代码可得cglib可以改变方法。
注意: 创建代理对象的目标对象(这里是CGlibSample)一定要有无参构造方法

2,InvocationHandler

这里的InvocationHandler接口并不是java反射包中的InvocationHandler,而是cglib中接口net.sf.cglib.proxy.InvocationHandler,其实里面的内容和java差不多,如下所示:


 public interface InvocationHandler extends Callback {
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;

}
    @Test
    public void testInvocationHandler(){

        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(CGlibSample.class);

        enhancer.setCallback(new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                /**
                 * method.getDeclaringClass() != Object.class  表示该方法不能是Object类中定义的方法,如:toString()。
                 * method.getReturnType() == String.class  表示方法的返回类型只能为String类型
                 */
                if (method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
                    return "Hello cglib!";
                } else {
                    return "do not know what to do";
                }
            }
        });

        CGlibSample proxy = (CGlibSample) enhancer.create();

        Assert.assertTrue("Hello cglib!".equals(proxy.test("hello!")));

        Assert.assertTrue("do not know what to do".equals(proxy.toString()));

    }

3,MethodInterceptor

    @Test
    public void testMethodInterceptor(){

        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(CGlibSample.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                if (method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
                    return "Hello cglib!";
                } else {
                    //这里有点像struts2中拦截器链
                    return proxy.invokeSuper(obj,args);
                }
            }
        });

        CGlibSample proxy = (CGlibSample) enhancer.create();

        Assert.assertTrue("Hello cglib!".equals(proxy.test("hello!")));

        Assert.assertFalse("do not know what to do".equals(proxy.toString()));
    }

4,CallbackFilter

接口CallbackFilter实现类CallbackHelper。

    @Test
    public void testCallbackFilter(){

        Enhancer enhancer = new Enhancer();

        CallbackHelper callbackHelper = new CallbackHelper(CGlibSample.class,new Class[0]) {
            @Override
            protected Object getCallback(Method method) {
                if (method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
                    return new FixedValue() {
                        @Override
                        public Object loadObject() throws Exception {
                            return "Hello cglib!";
                        }
                    };
                } else {
                    return NoOp.INSTANCE;
                }
            }
        };

        enhancer.setSuperclass(CGlibSample.class);
        enhancer.setCallbackFilter(callbackHelper);
        enhancer.setCallbacks(callbackHelper.getCallbacks());

        CGlibSample proxy = (CGlibSample) enhancer.create();

        Assert.assertTrue("Hello cglib!".equals(proxy.test("hello!")));
        System.out.println(proxy.hashCode());
        Assert.assertFalse("do not know what to do".equals(proxy.toString()));

注意:不要使用非静态的匿名内部类,会造成内存泄露。本文使用非静态的匿名内部类是为了方便。

5,Immutable Bean

    @Test(expected = java.lang.IllegalStateException.class)
    public void testImmutableBean(){

        SampleBean sampleBean = new SampleBean();

        sampleBean.setValue("Hello cglib");

        SampleBean immutableBean = (SampleBean) ImmutableBean.create(sampleBean);

        Assert.assertTrue("Hello cglib".equals(immutableBean.getValue()));

        sampleBean.setValue("Hello cglib again");
        Assert.assertTrue("Hello cglib again".equals(immutableBean.getValue()));

        immutableBean.setValue("Hello World!");//throw Exception java.lang.IllegalStateException: Bean is immutable
    }

6,Bean Generator

    @Test
    public void testBeanGenerator() throws Exception{

        BeanGenerator beanGenerator = new BeanGenerator();

        beanGenerator.addProperty("value",String.class);

        Object bean = beanGenerator.create();
        //获取bean的setter方法
        Method setter = bean.getClass().getMethod("setValue",String.class);
        setter.invoke(bean,"Hello cglib");

        //获取bean的getter方法
        Method getter = bean.getClass().getMethod("getValue");

        Assert.assertTrue("Hello cglib".equals(getter.invoke(bean)));


    }

7,Bean Copier

OtherSampleBean:

public class OtherSampleBean {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

测试案例:

    @Test
    public void testBeanCopier(){

        BeanCopier copier = BeanCopier.create(SampleBean.class,OtherSampleBean.class,false);

        SampleBean sampleBean = new SampleBean();
        sampleBean.setValue("sample bean");

        OtherSampleBean otherSampleBean = new OtherSampleBean();
        copier.copy(sampleBean,otherSampleBean,null);

        Assert.assertTrue("sample bean".equals(otherSampleBean.getValue()));
    }

8,Bulk Bean

    @Test
    public void testBulkBean(){

        BulkBean bulkBean = BulkBean.create(SampleBean.class,
                new String[]{"getValue"},
                new String[]{"setValue"},
                new Class[]{String.class});

        SampleBean bean = new SampleBean();
        bean.setValue("sample bean");

        Assert.assertTrue(bulkBean.getPropertyValues(bean).length == 1);

        Assert.assertTrue("sample bean".equals(bulkBean.getPropertyValues(bean)[0]));

        bulkBean.setPropertyValues(bean,new Object[]{"bulk bean"});

        Assert.assertTrue("bulk bean".equals(bean.getValue()));
    }

9,Bean Map

    @Test
    public void testBeanMap(){

        SampleBean bean = new SampleBean();

        BeanMap map = BeanMap.create(bean);
        bean.setValue("bean mao");

        Assert.assertTrue("bean mao".equals(map.get("value")));

    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值