【动态代理】CGLIB 动态代理的使用及原理

JDK动态代理和CGLIB动态代理 在SpringAOP中基于动态代理实现功能的增强,也就是动态的生成代理类,在代理类中织入增强的逻辑然后调用目标对象的方法。动态代理中用的比较多的两种:JDK动态代理、CGLIB动态代理。 JDK动态代理 使用JDK的java.lang.reflect.Proxy类的newProxyInstance方法实现的代理。 用一个测试接口看下具体实现: public interface JdkProxyDemoService { void queryTrs(); } @Service public 阅读详情

1. CGLIB 动态代理介绍

什么是 CGLIB?

CGLIB是一个功能强大,高性能的代码生成包。它为没有实现接口的类提供代理,为JDK的动态代理提供了很好的补充。

通常可以使用Java的动态代理创建代理,但当要代理的类没有实现接口或者为了更好的性能,CGLIB 是一个好的选择。

CGLIB 的原理

CGLIB 原理:动态生成一个要代理类的子类,子类重写要代理的类的所有不是 final 的方法。在子类中采用方法拦截的技术拦截所有父类方法的调用,顺势织入横切逻辑。

CGLIB 底层:采用ASM字节码生成框架,使用字节码技术生成代理类,比使用 Java 反射效率要高。

2. CGLIB 动态代理使用

CGLIB 动态代理步骤:

  1. 引入 CGLIB 依赖
  2. 定义一个被代理类
  3. 定义一个拦截器并实现接口 MethodInterceptor
  4. 代理工厂类
  5. 通过代理对象调用方法

引入依赖:cglib-nodep-2.2.jar

Student:被代理类

public class Student {

    public void handOut() {
        System.out.println("学生交作业。");
    }
}

CglibProxy:拦截器

public class CglibProxy implements MethodInterceptor {

    /**
     * @param o: 代理对象
     * @param method: 被代理方法
     * @param params: 方法入参
     * @param methodProxy: CGLIB方法
     **/
    @Override
    public Object intercept(Object o, Method method, Object[] params, MethodProxy methodProxy) throws Throwable {
        System.out.println("【增强方法】代理对象正在执行的方法:" + method.getName());
        Object result = methodProxy.invokeSuper(o, params);
        return result;
    }
}

CglibProxyFactory:代理工厂类

public class CglibProxyFactory {

    public static Object creatCglibProxyObj(Class<?> clazz) {
        Enhancer enhancer = new Enhancer();
        // 为加强器指定要代理的业务类(即为下面生成的代理类指定父类)
        enhancer.setSuperclass(clazz);
        // 设置回调:对于代理类上所有方法的调用,都会调用CallBack,而Callback则需要实现intercept()方法
        enhancer.setCallback(new CglibProxy());
        return enhancer.create();
    }

}

测试:

public class Test {

    public static void main(String[] args) {
        Student studentProxy = (Student)CglibProxyFactory.creatCglibProxyObj(Student.class);
        studentProxy.handOut();
    }

}

运行后,依旧可以增强原功能。

3. CGLIB 动态代理原理

上文中的是通过 enhancer.create 方法调用获取的代理对象,以此为入口深入探究一下 CGLIB 动态代理的实现原理。

Enhancer#create():

public Object create() {
    this.classOnly = false;
    this.argumentTypes = null;
    return this.createHelper();
}

Enhancer#createHelper():调用父类的 create() 方法

private Object createHelper() {
    //...

    return super.create(KEY_FACTORY.newInstance(this.superclass != null ? this.superclass.getName() : null, ReflectUtils.getNames(this.interfaces), 
    		this.filter, this.callbackTypes, this.useFactory, this.interceptDuringConstruction, this.serialVersionUID));
}

AbstractClassGenerator#create():

protected Object create(Object key) {
    try {
        //...
            if (gen == null) {
            	// 1.生成代理类 
                byte[] b = this.strategy.generate(this);
                // 2.获取代理类名称
                String className = ClassNameReader.getClassName(new ClassReader(b));
                this.getClassNameCache(loader).add(className);
                gen = ReflectUtils.defineClass(className, b, loader);
            }

            if (this.useCache) {
                ((Map)cache2).put(key, new WeakReference(gen));
            }

            var24 = this.firstInstance(gen);
        } finally {
            CURRENT.set(save);
        }

        return var24;
    }
    //...
}

DefaultGeneratorStrategy#generate():生成代理类

public byte[] generate(ClassGenerator cg) throws Exception {
    ClassWriter cw = this.getClassWriter();
    this.transform(cg).generateClass(cw);
    return this.transform(cw.toByteArray());
}

DebuggingClassWriter#toByteArray():

public byte[] toByteArray() {
    return (byte[])((byte[])AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            byte[] b = DebuggingClassWriter.super.toByteArray();
            if (DebuggingClassWriter.debugLocation != null) {
                String dirs = DebuggingClassWriter.this.className.replace('.', File.separatorChar);

                try {
                	// 如果 DebuggingClassWriter.DEBUG_LOCATION_PROPERTY 系统属性被设置,则输出代理类到指定目录
                    (new File(DebuggingClassWriter.debugLocation + File.separatorChar + dirs)).getParentFile().mkdirs();
                    File file = new File(new File(DebuggingClassWriter.debugLocation), dirs + ".class");
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));

                    try {
                        out.write(b);
                    } finally {
                        out.close();
                    }

                    if (DebuggingClassWriter.traceEnabled) {
                        file = new File(new File(DebuggingClassWriter.debugLocation), dirs + ".asm");
                        out = new BufferedOutputStream(new FileOutputStream(file));

                        try {
                            ClassReader cr = new ClassReader(b);
                            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
                            TraceClassVisitor tcv = new TraceClassVisitor((ClassVisitor)null, pw);
                            cr.accept(tcv, 0);
                            pw.flush();
                        } finally {
                            out.close();
                        }
                    }
                } catch (IOException var17) {
                    throw new CodeGenerationException(var17);
                }
            }

            return b;
        }
    }));
}

生成 CGLIB 字节码文件

由上文可知,把 DebuggingClassWriter.DEBUG_LOCATION_PROPERTY(也就是 cglib.debugLocation)系统属性设置为当前项目的根目录,即可保存 CGLIB 生成的代理类到当前项目根目录下。

设置系统属性配置:

public static void main(String[] args) {
    System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, System.getProperty("user.dir"));
    Student studentProxy = (Student)CglibProxyFactory.creatCglibProxyObj(Student.class);
    studentProxy.handOut();
}

运行代码:
在这里插入图片描述
生成的动态代理类为:

public class Student$$EnhancerByCGLIB$$723acbd8 extends Student implements Factory {
    
    private boolean CGLIB$BOUND;
    private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
    private static final Callback[] CGLIB$STATIC_CALLBACKS;
    private MethodInterceptor CGLIB$CALLBACK_0;
    private static final Method CGLIB$handOut$0$Method;
    private static final MethodProxy CGLIB$handOut$0$Proxy;
    //...

    static void CGLIB$STATICHOOK1() {
        CGLIB$THREAD_CALLBACKS = new ThreadLocal();
        CGLIB$emptyArgs = new Object[0];
        Class var0 = Class.forName("com.zzc.proxy.cglib.Student$$EnhancerByCGLIB$$723acbd8");
        Class var1;
        Method[] var10000 = ReflectUtils.findMethods(new String[]{"finalize", "()V", "equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
        CGLIB$handOut$0$Method = ReflectUtils.findMethods(new String[]{"handOut", "()V"}, (var1 = Class.forName("com.zzc.proxy.cglib.Student")).getDeclaredMethods())[0];
        CGLIB$handOut$0$Proxy = MethodProxy.create(var1, var0, "()V", "handOut", "CGLIB$handOut$0");
        //...
    }

    final void CGLIB$handOut$0() {
        super.handOut();
    }

    public final void handOut() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$handOut$0$Method, CGLIB$emptyArgs, CGLIB$handOut$0$Proxy);
        } else {
            super.handOut();
        }
    }
    
	//...

    static {
        CGLIB$STATICHOOK1();
    }
}

说明:

  1. 生成的动态代理类继承了父类 Student,并且实现了接口 Factory
  2. 动态代理类持有 MethodInterceptor
  3. 动态代理类会重写父类 Student 的非 final、private 方法;也会构建自己的方法(cglib 方法),构建方式:CGLIB”+“$父类方法名$
  4. cglib 方法的方法体:super.方法名,直接调用父类;重写方法:它会调用拦截器中的 intercept() 方法
  5. methodProxy.invokeSuper() 方法会调用动态代理类中的 cglib 方法;methodProxy.invoke() 方法会调用动态代理类中的重写方法

CGLIB 动态代理原理:外界调用了方法后(studentProxy.handOut();),由于父类 Student 被子类(动态代理类)给继承了(已经重写了 handOut()),所以,会调用动态代理类中的 handOut() 方法。而在这个重写的方法中,又会去调用 MethodInterceptor#intercept() 方法。在这个方法中,功能增强后,再去调用动态代理中的 cglib 方法,而此方法又会去调用父类中的方法。

4. JDK 动态代理和 CGLIB 动态代理比较

4.1 区别

总结一下两者的区别吧:

  1. JDK 动态代理基于接口,CGLIB 动态代理基于类。因为 JDK 动态代理生成的代理类需要继承 java.lang.reflect.Proxy,所以,只能基于接口;CGLIB 动态代理是根据类创建此类的子类,所以,此类不能被 final 修饰
  2. JDK 和 CGLIB 动态代理都是在运行期生成字节码。而 JDK 是直接写 Class 字节码;而 CGLIB 使用 ASM 框架写 Class 字节码(不鼓励直接使用ASM,因为它要求你必须对 JVM 内部结构包括 class 文件的格式和指令集都很熟悉)
  3. JDK 通过反射调用方法,CGLIB 通过 FastClass 机制(下一篇再将)直接调用方法。所以,CGLIB 执行的效率较高
  4. JDK 动态代理是利用反射机制生成一个实现代理接口的类(这个类看不见摸不着,在 jvm 内存中有这个类),在调用具体方法前调用 InvokeHandler来处理。核心是实现 InvocationHandler接口,使用 invoke()方法进行面向切面的处理,调用相应的通知;CGLIB 动态代理是利用 asm 开源包,对代理对象类的 class 文件加载进来,通过修改其字节码生成子类来处理。核心是实现 MethodInterceptor 接口,使用 intercept() 方法进行面向切面的处理,调用相应的通知。

4.2 优缺点

劣势:

  1. JDK:JDK的动态代理机制只能代理实现了接口的类,而不能实现接口的类就不能实现JDK的动态代理
  2. CGLIB:CGLIB 的原理是对指定的目标类生成一个子类,并覆盖其中方法实现增强,但因为采用的是继承,所以不能对 final 修饰的类进行代理

优势:

  1. JDK:最小化依赖关系,减少依赖意味着简化开发和维护,JDK本身的支持,可能比 cglib 更加可靠
  2. JDK:平滑进行JDK版本升级,而字节码类库通常需要进行更新以保证在新版Java 上能够使用。代码实现简单
  3. CGLIB:从某种角度看,限定调用者实现接口是有些侵入性的实践,类似cglib动态代理就没有这种限制。只操作我们关心的类,而不必为其他相关类增加工作量。另外高性能。

5. 动态代理在 Spring 中的应用

Spring 应用:

  1. 如果目标对象实现了接口,默认情况下 Spring 会采用 JDK 的动态代理实现 AOP
  2. 如果目标对象实现了接口,Spring 也可以强制使用 CGLIB 实现 AOP
  3. 如果目标对象没有实现接口,必须采用 CGLIB 实现动态代理,当然 Spring 可以在 JDK 动态代理和 CGLIB 动态代理之间转换
CGLIB(Code Generation Library)详解 什么是CGLIB CGLIB是一个强大的、高性能的代码生成库。其被广泛应用于AOP框架(Spring、dynaop)中,用以提供方法拦截操作。Hibernate作为一个比较受欢迎的ORM框架,同样使用CGLIB来代理单端(多对一和一对一)关联(延迟提取集合使用的另一种机制)。CGLIB作为一个开源项目,其代码托管在github,地址为:https://github.com/cglib/cglib为什么 阅读详情

相关推荐

cglib 动态代理原理详解

cglib 动态代理详解 我们都知道jdk的动态代理内部调用切面无效的问题,而cglib则不会出现这种情况,这是为什么?cglib就一定不会出现内部调用切面无效的问题吗?cglib针对每一个类只创建了一个代理类吗?为什么cglib的效率要比jdk的动态代理低呢? 首先我们看一下通常我们是如何使用cglib增强一个类的 public class Main { static class Test{ public void test(){ System.out.pr

u012094957的专栏 1269

【深度思考】聊聊CGLIB动态代理原理

聊聊CGLIB动态代理原理。

申城异乡人 2787

深入理解动态代理:JDK动态代理与CGLIB动态代理

动态代理是一种在运行时创建代理对象的技术,通过代理对象来控制对原对象的访问,能够在不修改原对象的情况下添加额外的功能。JDK动态代理:基于Java反射机制,只能代理实现了接口的类。CGLIB动态代理:基于字节码生成技术,可以代理没有实现接口的类。// 抽象主题接口动态代理在Java中提供了一种灵活而强大的机制,能够在运行时为目标对象添加额外的功能。JDK动态代理和CGLIB动态代理各有优势和适用场景,开发者可以根据具体需求选择合适的代理机制。希望这篇文章对你理解动态代理有所帮助。

捕风捉你 · 星桥API接入与大模型实战 3149

CGLIB动态代理详解分析

CGLIB是强大的、高性能的代码生成库,被广泛应用于AOP框架,它底层使用ASM来操作字节码生成新的类,为对象引入间接级别,以控制对象的访问。CGLIB相比于JDK动态代理更加强大,JDK动态代理只能对接口进行代理,而CGLIB既可以代理普通类,也能够代理接口。

weixin_43397326的博客 6586

无人机+消防车:高楼灭火系统技术详解

传统的消防设备,如登高车、车载水枪、水炮和高喷车,在50米以上高度的火源面前往往力不从心,100米以上高层火灾则更加依赖消防员“爬楼”灭火,效率低下且风险极高。消防水带:采用聚乙烯丝材质,超轻、耐腐蚀、强度高,能够携带大量水或灭火泡沫进行高空喷水灭火作业。“无人机+消防车”高楼灭火系统主要由消防车和无人机两部分组成,通过机车联动实现高效灭火。高效灭火:无人机能够快速到达高层建筑顶部或指定位置进行灭火作业,大大提高了灭火效率。空压泡沫系统:配备超大水箱,支持长时间供应灭火泡沫,满足无人机灭火剂的需求。

专注多旋翼、复合翼无人机技术研究,从事低空经济行业。 1663

从ACTF2020看文件上传漏洞:你以为改后缀就完事了?这些坑我都帮你踩过了

本文通过ACTF2020的Upload题目深入剖析文件上传漏洞的复杂性和防御策略。文章揭示了常见误区,如仅修改文件后缀的局限性,并详细解析了绕过技巧和高级防御机制。从开发角度提供了构建安全上传功能的实用建议,帮助读者全面理解文件上传漏洞的本质与防护方法。

weixin_29278805的博客 235

【Spring】Spring AOP底层原理:JDK动态代理和CGLIB动态代理

Spring AOP 的实现原理是基于动态代理和字节码操作的。而动态代理是基于反射机制的。 在编译时, Spring 会使用 AspectJ 编译器将切面代码编译成字节码文件。在运行时, Spring 会使用 Java 动态代理或 CGLIB 代理生成代理类,这些代理类会在目标对象方法执行前后插入切面代码,从而实现AOP的功能。

m0_65277261的博客 3707

innovus实战攻略 | 用setUsefulSkewMode解锁时序优化的“隐藏技能”!

就像时序优化的“瑞士军刀”,参数虽多,但掌握了分类逻辑后,用起来其实很简单!如果你有更绝的用法,欢迎在评论区分享,大家一起卷起来!简单来说,它就是时序优化的“乾坤大挪移”。通过调整触发器的时钟到达时间,把关键路径的建立时间“借”给非关键路径,从而实现全局时序收敛。别急,这个命令就是你的“时序救星”!(工具最多只能借1.2ns的裕量,防止“借过头”导致新问题!这个参数能帮你兜底!(对关键路径“下死手”,确保优化到位!(设置上限,给工具套上“紧箍咒”!(直接跳过边界,避免优化反噬!(全局管理,防止“借过头”!

weixin_50820814的博客 1346

CGLib动态代理原理

CGLib动态代理原理 CGLib动态代理是代理类去继承目标类,然后重写其中目标类的方法啊,这样也可以保证代理类拥有目标类的同名方法; 看一下CGLib的基本结构,下图所示,代理类去继承目标类,每次调用代理类的方法都会被方法拦截器拦截,在拦截器中才是调用目标类的该方法的逻辑,结构还是一目了然的; 1.CGLib的基本使用 使用一下CGLib,在JDK动态代理中提供一个Proxy类来创建代理类,而在CGLib动态代理中也提供了一个类似的类Enhancer; 使用的CGLib版本是2.2.2,我是随便找的,不

坚定目标,超越自我 5097

论文理解【LLM-OR】——【OptMATH】A Scalable Bidirectional Data Synthesis Framework for Optimization Modeling

本文提出 LLM-OR 领域的双向数据合成框架 OptMATH,从已有 MF/PD 出发反向生成 NL,再使用 AutoFormulator 进行正向建模,通过最优值匹配 rejection sampling 确保语义一致性。实现了难度可控的语义一致数据合成

佚失的诗篇 489

量化回测框架三选一:Backtrader、Zipline、PyAlgoTrade,新手到底该跟谁学?

本文对比分析了三大量化回测框架Backtrader、Zipline和PyAlgoTrade,帮助新手选择最适合的入门工具。从安装配置、策略编写到文档查阅,详细解析各框架的特点和适用场景,为量化交易初学者提供实用指南。

weixin_28745309的博客 262

CGLIB 动态代理及其原理分析

一、简介   CGLIB,即 Code Generation Library,是一个强大的、高性能的代码生成库。它可以在运行期扩展 Java 类与实现 Java 接口(JDK 动态代理只能用于接口),它被许多 AOP 框架广泛地使用,如为 Spring AOP 提供方法的 interception(拦截),被 Hibernate 用来代理单端(多对一和一对一)关联(延迟提取集合使用的另一种机制)。本文使用的 CGLIB 依赖如下: <dependency> <groupId>

weixin_41427129的博客 6204

LFI Scanner 本地文件包含漏洞扫描、文件路径遍历、敏感文件读取(etcpasswd)

✅ **敏感文件读取验证**:内置`/etc/passwd、/windows/system32/drivers/etc/hosts、phpinfo.php`等敏感文件字典,一键验证漏洞可利用性;🔴 **Windows**:`/windows/win.ini`(系统配置)、`/windows/system32/drivers/etc/hosts`;🔴 **Linux**:`/etc/passwd`(用户信息)、`/proc/version`(内核版本)、`/etc/hosts`(域名解析);

寒寒豆豆软件公司的博客 125

CGLIB动态代理实现原理

一、CGLIB介绍 CGLIB(Code Generation Library)是一个开源项目!是一个强大的,高性能,高质量的Code生成类库,它可以在运行期扩展Java类与实现Java接口。Hibernate用它来实现PO(Persistent Object 持久化对象)字节码的动态生成。 CGLIB是一个强大的高性能的代码生成包。它广泛的被许多AOP的框架使用,例如Spring AOP为他...

AN_ERA的博客 1111

后悔没早点知道!用AI只需四步,一次性讲清高质量论文引言写法(附公式+AI指令)

帮我写SCI 论文撰写引言的“研究背景与重要性”,要求从本研究所属领域的小背景切入,使用现在时态描述该领域的总体状况与发展趋势,突出其在学术研究、实际应用或社会层面的重要价值,并通过一个吸引人的钩子开头,如关键事实、现实问题或学术热点,引导读者关注本主题的重要性。梳理你所在领域和你研究相关的关键成果,但不能罗列所有文献,重点抓核心脉络,这部分最重要的实际上是让你了解别人的研究脉络,然后在每个关键的节点上,引用几篇关键参考文献作支撑,来体现你对领域的熟悉度就可以了。3)研究缺口模糊,没法突出问题的真实价值;

qq_64378896的博客 101

【DaVinci Developer专题】-41-APP SWC如何读取写入NVM Block数据

APP SWC Port如何Read读取/Write写入NVM Block数据; DaVinci Developer中的Calibration Parameter/Per-Instance Memory/Service Need如何配置。

「汽车电子助手」的博客 4457

动态代理:Cglib原理讲解

Cglib动态代理不需要被代理类实现接口,根据原理我们知道生成的代理类是继承了被代理类,而且其方法调用方法是使用FastClass,这与JDK动态代理的反射有比较大的区别。JDK代理使用的是反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。CGLIB代理使用字节码处理框架ASM,对代理对象类的class文件加载进来,通过修改字节码生成子类。JDK创建代理对象效率较高,执行效率较低;CGLIB创建代理对象效率较低,执行效率高。

猪大肠的博客 1408

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

【Spring基础】CGLIB动态代理实现原理

前言 Github:https://github.com/yihonglei/thinking-in-spring 一 CGLIB介绍 CGLIB(Code Generation Library)是一个开源项目!是一个强大的,高性能,高质量的Code生成类库, 它可以在运行期扩展Java类与实现Java接口。Hibernate用它来实现PO(Persistent Object 持久化对象)...

yhl_jxy的博客 8万+

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

CGLIB动态代理底层实现原理

一、前言 最近在探究Spring AOP的性能,发现最后是绕不开JDK动态代理和CGLIB动态代理这两个点。笔者心里大致有这么个概念:对于动态代理来说,CGLIB性能要好于JDK。也知道CGLIB是利用ASM技术基于继承子类实现动态代理,JDK是基于实现接口实现动态代理,但是对于底层实现还是比较模糊。今天就彻底整明白CGLIB动态代理的底层实现。二、前置准备(一)测试代码CGLIB核心的几个概念...

wajueji的博客 934

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

cglib动态代理实现原理_全面解析动态代理 JDK Proxy 及 CGLib 原理

@本文阅读大概需要6分钟1 什么是代理 代理的目标是为某一个对象提供一个代理,并由代理对象来控制对原对象的访问。依据代理类的创建时间,分为静态代理和动态代理。静态代理是在程序运行前就已经存在代理类的字节码文件,代理类和委托类的关系在运行前已经确定好。动态代理是程序在运行期间动态构建代理对象和动态调用代理方法的一种机制。在程序运行时,通过反射机制动态创建而成。简单地说,代理是用来在被代理对...

weixin_32716541的博客 1455

Cglib动态代理实现原理

Cglib动态代理实现原理: 我们先通过一个demo看一下Cglib是如何实现动态代理的。 首先定义个服务类,有两个方法并且其中一个方法用final来修饰。 public class PersonService { public PersonService() { System.out.println("PersonService构造"); } //该方法不...

黄亚的博客 348

CGLIB动态代理的实现及原理

CGLIB介绍与原理(部分节选自网络)一、什么是CGLIB?CGLIB是一个功能强大,高性能的代码生成包。它为没有实现接口的类提供代理,为JDK的动态代理提供了很好的补充。通常可以使用Java的动态代理创建代理,但当要代理的类没有实现接口或者为了更好的性能,CGLIB是一个好的选择。二、CGLIB原理CGLIB原理:动态生成一个要代理类的子类,子类重写要代理的类的所有不是final的方法。在子类中...

留下你的观点 601

JDK动态代理 和CGLib动态代理实现原理和两者的区别

JDK动态代理和CGLib动态代理

zeng2813的博客 1090

jdk与cglib动态代理及原理

Spring的AOP在运行时多以jdk及cglib动态代理来实现

KEEP CODING 1026
上一篇: 【动态代理】JDK 动态代理的使用及原理
下一篇: 【SpringBoot】SpringBoot 中的 切面 AOP + 自定义注解
sco5282
博客等级 码龄5年 844粉丝 154原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值