CGlib 入门

CGlib 入门CGlib入门cglibgithub地址链接。项目maven构建:cglibcglib3.1项目gradle构建:dependencies{compile’cglib:cgl

大家好,又见面了,我是你们的朋友全栈君。

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")));

    }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/135174.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • CSS-圆角边框

    CSS-圆角边框掌握了圆角边框的内容就可以做出类似百度搜索框的效果来代码 DOCTYPE tml htmllang en head metacharset UTF 8 metahttp equiv X UA Compatible content IE edge metahttp equiv X UA Compatible content IE edge metacharset UTF 8 head htmllang en

    2025年6月11日
    0
  • ORBSLAM2学习(一):ORB算法原理[通俗易懂]

    ORBSLAM2学习(一):ORB算法原理[通俗易懂]前言目前学习ORBSLAM2中,ORBSLAM2中使用ORB算子进行特征点的提取与描述,ORB算法原理主要来自于文章《ORBanefficientalternativetoSIFTorSURF》。这里先就该文章做自己的学习过程记录,之后结合文章内容分析ORBSLAM2中的代码实现(放到下一篇博客中)。本文把文章《ORBanefficientalternative……

    2022年10月25日
    0
  • RPA中, COE是什么意思? 它的职责是什么?[通俗易懂]

    COE,是指RPA卓越中心,即CenterofExcellence,简称COE,是企业早期部署RPA时创建的部门,用于支持RPA的实现和正在进行的部署。一个企业要想顺利实施RPA,为企业后续RPA的部署打下良好基础,其关键推动因素之一,是要建立一个结构良好且人员配置完善的RPA卓越中心(COE)。为了实现这一目标,RPA厂商应该协助客户在机器人流程自动化过程中开发内部自我维持和可扩展的RPA专业知识,以运行和维护机器人。卓越中心(COE)本质上是将RPA深入有效地嵌入组织,并在未来部署中重新分配累积的知

    2022年4月18日
    208
  • php 文件头部(header)信息详解

    php 文件头部(header)信息详解

    2021年8月29日
    62
  • JAVA校园二手交易平台

    JAVA校园二手交易平台本系统主要面向于大学校园网用户,依托校园网提供给这些用户一个发布和交流二手商品信息的平台。在大学校园里,存在着很多的二手商品,但是由于信息资源的不流通以及传统二手商品信息交流方式的笨拙,导致了很多仍然具有一定价值或者具有非常价值的二手商品的囤积,乃至被当作废弃物处理。现在通过校园网进入到本系统,可以方便快捷的发布和交流任何二手商品的信息,并且可以通过留言方式进行深一步的交流。由于每个大学的校园网都…

    2022年6月15日
    23
  • sftp上传本地文件_sftp连接超时原因

    sftp上传本地文件_sftp连接超时原因关键:(1)sftp的测试指令:sftp-oPort=2125meituan@220.248.104.170(2)让上海那边自己试了一下,也不行,他们自己重置了一下sftp的密码,我们可以登录了;上海那边反应,在10月10号早上,大量重复数据发送到上海政府端,查询后发现在:dx-qcs-regulation-shanghai06这个主机有问题:里面有大量的…

    2022年9月14日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号