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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 连接失败连接区间变量

    连接失败连接区间变量

    2022年1月12日
    48
  • 对cms的一些感想英文_CMS概念

    对cms的一些感想英文_CMS概念在很久以前开个网站基本上只有技术人员才可以实现的,曾几何时出现的cms系统,使架设网站的技术门槛大大的降低,只要有个空间,有个域名,会打字就可以开网站,后来又出来了web2.0,blog。但是毕竟这些都是一些商业炒作。记得当初最先使用的网站管理系统使动易,当时的动易因为盗版的问题采用动易组件,虽然网站制作很容易但是因为动易组件的问题造成服务…

    2022年10月19日
    0
  • 卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!

    卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!作者|Rocky0429来源|Python空间大家好,我是Rocky0429,一个喜欢在网上收集各种资源的蒟蒻…网上资源眼花缭乱,下载的方式也同样千奇百怪,比如BT下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的x雷和某度网盘成了我经常使用的工具。作为一个没有钱的穷鬼,某度网盘几十kb的下载速度让我…

    2022年6月14日
    31
  • 哈希表与哈希冲突(手动实现哈希桶)

    哈希表与哈希冲突(手动实现哈希桶)一直在说哈希,你还记得哈希冲突吗?尝试过自己手动实现哈希桶来解决哈希冲突吗?挑战一下,你会发现源码也没那么难,嘻嘻?

    2025年7月24日
    1
  • currentstyle 织梦_织梦导航高亮标签currentstyle调用自定义字段的方法

    currentstyle 织梦_织梦导航高亮标签currentstyle调用自定义字段的方法用织梦仿站时候,经常会使用currentstyle标签高亮当前的栏目,具体代码为:currentstyle=’~typename~’但是在实际建站操作中经常调用自定义字段,大家会发现在用currentstyle的时候读取不出自定义字段的内容了。这时候,我们就需要对织梦进行二次开发,以满足我们的需要。1、我们打开/include/taglib/channel.lib.php文件,在136行找到:$r…

    2022年7月14日
    22
  • executescalar mysql_ExecuteScalar

    executescalar mysql_ExecuteScalar这两个答案和一点点思考使我想到了一个接近答案的东西。首先再澄清一下:该应用程序是用C#(2.0+)编写的,并使用ADO.NET与SQLServer2005进行通信。镜像设置是托管主体和镜像的两个W2k3服务器以及托管作为监视器的快速实例的第三个服务器。这样做的好处是,故障转移对于使用数据库的应用程序几乎是透明的,它将对某些连接引发错误,但从根本上讲一切都会很好地进行。是的,我们得到了奇怪的误报…

    2022年6月30日
    18

发表回复

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

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