bytebuddy实现原理分析 &源码分析 (三)- advice 详解

bytebuddy之advice详解 & 注解详解 注解列表一、 注解列表二、 demo 解析 一、 注解列表 注解 值 @OnMethodEnter 表示这个方法会在,进入目标方法时调用,这个注解声明的方法必须是static。当目标的方法是constructor构造器时,@This只能写field,不能读field,或者调用方法 skipOn() 跳过一些方法 prependLineNumber() 如果为true,会改目标方法的行号 inline() 标识方法应该被内联到目标的方法中去 suppress() 忽 阅读详情

bytebuddy实现原理分析 &源码分析(一)
bytebuddy实现原理分析 &源码分析 (二)
bytebuddy实现原理分析 &源码分析 (三)
bytebuddy实现原理分析 &源码分析 (四)

八、advice

增强,切面编程。
asm入门
asm手册
大致了解了asm,就可以知道Visitor是asm进行读写解析.class字节码文件的核心api。切面的原理就是匹配所有的方法,在方法前后加入额外的方法,AdviceAdapter类提供了onMethodEnter和onMethodExit两个方法,实现就可以做到简单的切面。

bytebuddy 的增强就是基于 asm的core API然后提供了一些列注解,方法用户使用。
在这里插入图片描述

8.1 AsmVisitorWrapper

就是对visitor的一个封装。
visitor以分为 ClassReader和ClassWriter。

首先 提供了一个字段 flags:代表了标志。
在这里插入图片描述

核心方法

  • int mergeWriter(int flags); 合并写标记 flags|foo
  • int mergeReader(int flags); 合并读标记
  • ClassVisitor wrap(TypeDescription instrumentedType,
    ClassVisitor classVisitor,
    Implementation.Context implementationContext,
    TypePool typePool,
    FieldList<FieldDescription.InDefinedShape> fields,
    MethodList<?> methods,
    int writerFlags,
    intreaderFlags);
    把一个DynamicType定义的类,使用ClassVisitor生成字节码。
    instrumentedType ,被修改的类型;implementationContext,就是定义了改动的字节码实现;TypePool 缓存池;MethodList 方法列表;

8.1.1 ForDeclareFields

在这里插入图片描述

8.1.1.1 Entry
  • matcher 用来命中的对象
  • FieldVisitorWrapper 的 封装了要被修改filed对应的Vistor。

这个类的作用是报存 matcher和visitor的对应关系。使用matcher命中被修改的区域,visitor来应用修改逻辑。

        protected static class Entry implements ElementMatcher<FieldDescription.InDefinedShape>, FieldVisitorWrapper {
   
   

            /**
             * The matcher to identify fields to be wrapped.
             */
            private final ElementMatcher<? super FieldDescription.InDefinedShape> matcher;

            /**
             * The field visitor wrapper to be applied if the given matcher is matched.
             */
            private final List<? extends FieldVisitorWrapper> fieldVisitorWrappers;

            /**
             * Creates a new entry.
             *
             * @param matcher              The matcher to identify fields to be wrapped.
             * @param fieldVisitorWrappers The field visitor wrapper to be applied if the given matcher is matched.
             */
            protected Entry(ElementMatcher<? super FieldDescription.InDefinedShape> matcher, List<? extends FieldVisitorWrapper> fieldVisitorWrappers) {
   
   
                this.matcher = matcher;
                this.fieldVisitorWrappers = fieldVisitorWrappers;
            }

            /**
             * {@inheritDoc}
             */
            public boolean matches(FieldDescription.InDefinedShape target) {
   
   
                return target != null && matcher.matches(target);
            }

            /**
             * {@inheritDoc}
             */
            public FieldVisitor wrap(TypeDescription instrumentedType, FieldDescription.InDefinedShape fieldDescription, FieldVisitor fieldVisitor) {
   
   
                for (FieldVisitorWrapper fieldVisitorWrapper : fieldVisitorWrappers) {
   
   
                    fieldVisitor = fieldVisitorWrapper.wrap(instrumentedType, fieldDescription, fieldVisitor);
                }
                return fieldVisitor;
            }
        }
8.1.1.2 DispatchingVisitor

继承ClassVisitor方法

  protected class DispatchingVisitor extends ClassVisitor {
   
   

            /**
             * The instrumented type.
             */
            private final TypeDescription instrumentedType;

            /**
             * A mapping of fields by their name and descriptor key-combination.
             */
            private final Map<String, FieldDescription.InDefinedShape> fields;

            /**
             * Creates a new dispatching visitor.
             */
            protected DispatchingVisitor(ClassVisitor classVisitor, TypeDescription instrumentedType, Map<String, FieldDescription.InDefinedShape> fields) {
   
   
                super(OpenedClassReader.ASM_API, classVisitor);
                this.instrumentedType = instrumentedType;
                this.fields = fields;
            }

            @Override
            public FieldVisitor visitField(int modifiers, String internalName, String descriptor, String signature, Object defaultValue) {
   
   
                FieldVisitor fieldVisitor = super.visitField(modifiers, internalName, descriptor, signature, defaultValue);
                FieldDescription.InDefinedShape fieldDescription = fields.get(internalName + descriptor);
                if (fieldVisitor != null && fieldDescription != null) {
   
   
                    for (Entry entry : entries) {
   
   
                        if (entry.matches(fieldDescription)) {
   
   
                            fieldVisitor = entry.wrap(instrumentedType, fieldDescription, fieldVisitor);
                        }
                    }
                }
                return fieldVisitor;
            }
        }
  • instrumentedType ,是被修改的类。
  • fields, 一个map结构,一个fields。
  • visitField,使用entry.wrap最终将fieldVisitor 委托给FieldVisitorWrapper接口。所以FieldVisitorWrapper的子类只要实现FieldVisitorWrapper的wrap方法,在其中定义具体的修改逻辑。
  public interface FieldVisitorWrapper {
   
   

            /**
             * Wraps a field visitor.
             *
             * @param instrumentedType The instrumented type.
             * @param fieldDescription The field that is currently being defined.
             * @param fieldVisitor     The original field visitor that defines the given field.
             * @return The wrapped field visitor.
             */
            FieldVisitor wrap(TypeDescription instrumentedType, FieldDescription.InDefinedShape fieldDescription, FieldVisitor fieldVisitor);
        }
8.1.1.3 ForDeclaredField 的内部实现

也是封装了上面提到的类

   class ForDeclaredFields extends AbstractBase {
   
   

        /**
         * The list of entries that describe matched fields in their application order.
         */
        private final List<Entry> entries;

        /**
         * Creates a new visitor wrapper for declared fields.
         */
        public ForDeclaredFields() {
   
   
            this(Collections.<Entry>emptyList());
        }

        /**
         * Creates a new visitor wrapper for declared fields.
         *
         * @param entries The list of entries that describe matched fields in their application order.
         */
        protected ForDeclaredFields(List<Entry> entries) {
   
   
            this.entries = entries;
        }

        /**
         * Defines a new field visitor wrapper to be applied if the given field matcher is matched. Previously defined
         * entries are applied before the given matcher is applied.
         *
         * @param matcher             The matcher to identify fields to be wrapped.
         * @param fieldVisitorWrapper The field visitor wrapper to be applied if the given matcher is matched.
         * @return A new ASM visitor wrapper that applied the given field visitor wrapper if the supplied matcher is matched.
         */
        public ForDeclaredFields field(ElementMatcher<? super FieldDescription.InDefinedShape> matcher, FieldVisitorWrapper... fieldVisitorWrapper) {
   
   
            return field(matcher, Arrays.asList(fieldVisitorWrapper));
        }

        /**
         * Defines a new field visitor wrapper to be applied if the given field matcher is matched. Previously defined
         * entries are applied before the given matcher is applied.
         *
         * @param matcher              The matcher to identify fields to be wrapped.
         * @param fieldVisitorWrappers The field visitor wrapper to be applied if the given matcher is matched.
         * @return A new ASM visitor wrapper that applied the given field visitor wrapper if the supplied matcher is matched.
         */
        public ForDeclaredFields field(ElementMatcher<? super FieldDescription.InDefinedShape> matcher, List<? extends FieldVisitorWrapper> fieldVisitorWrappers) {
   
   
            return new ForDeclaredFields(CompoundList.of(entries, new Entry(matcher, fieldVisitorWrappers)));
        }

        /**
         * {@inheritDoc}
         */
        public ClassVisitor wrap(TypeDescription instrumentedType,
                                 ClassVisitor classVisitor
字节码编程bytebuddy之通过Advice动态修改方法参数值 本文看下如何通过bytebuddy的advice切面技术来动态修改方法入参值。 阅读详情

相关推荐

bytebuddy实现原理分析 &源码分析 (一)

本文介绍byte buddy的源码。 byte buddy 是 新一代用于动态修改字节码的工具。 官方文档过于老旧和简陋,想要更好的使用 byte buddy 需要阅读源码。 dep 是byte buddy的开发包,实现都在里面。 码非常复杂。源码的编写是递进的,从对java的类型进行封装,到类的动态定义,运行时的加载,以及如何匹配修改字节码。 但是作者明显是对jvm的知识非常了解,作者很清楚字节码在jvm的加载原理 & 很清楚添加或减少类的成员,到底应该对字节码做些什么,所以很难要从这个角度去分析源码。

wanxiaoderen的博客 6451

Java字节码增强技术Bytebuddy探路篇

目录最近为了实现Java应用RPC调用的录制和Mock回放,需要以无侵入方式获取到RPC方法的出入参数和返回响应消息等数据,于是踏上了Java字节码增强技术的道路摸索,这个非常类似Trace所使用的相关技术,不过需要深入到RPC方法级别,对指定方法进行无侵入方式切面处理。先后对ASM/Javaassist/Bytebuddy等技术进行了调研等,本文是对所做摸索探路工作的总结,若读者有类似Trace场景需求,可以进行借鉴参考。在众多比较之后最后选择的是Bytebuddy技术。Java字节码是众多字节码增强技术

m0_71777195的博客 2118

Java中级开发工程师面试核心考察维度与高频问题解析

Java作为企业级开发的主流语言,其并发编程和集合框架是面试必考重点。HashMap作为核心数据结构,JDK8通过引入红黑树优化了哈希冲突处理,与ConcurrentHashMap的线程安全实现形成对比。在并发领域,线程池参数配置和锁机制选择直接影响系统性能,合理使用CountDownLatch等工具类能有效协调多线程任务。Spring框架的IoC容器初始化过程和AOP代理机制体现了设计模式的精妙应用,而事务传播行为的理解对保证数据一致性至关重要。掌握这些原理不仅能应对技术面试,更能指导实际工程中的架构设计

weixin_30617737的博客 297

bytebuddy实现原理分析 &源码分析 (二)

bytebuddy实现原理分析 &amp;源码分析四、字节码的操作(implementation ) pkg4.1 bytecode :pkg4.1.1 StackManipulation :cls4.1.1.1 StackManipulation的子类实现4.1.2 assign :pkg4.1.2.1 Assigner : cls1 Typing: in &amp; cls2 核心方法: in3 EqualTypesOnly : in &amp; impl4 Refusing : in &amp; im

wanxiaoderen的博客 3021

bytebuddy源码解析

bytebuddy 进阶一、ByteBuddyAgent示例1.1 Attacher 负责启动agent.jar1.2 Intaller Instrumention对象的载体很简单的getInstrumentionpremain agentmain1.3 VirtualMachine jvm平台的支持Resover获取 jvm平台信息OPENJ9HotSpot1.4 ByteBuddyAgent(核心)Provider1. ProceessProvider2. AttachmentProvider3. Ag

wanxiaoderen的博客 1841

分布式追踪 SkyWalking 源码分析七 agent和byteBuddy 原理

JVM 源码分析之 javaagent 原理完全解读 javaagent 的主要功能如下: 可以在加载 class 文件之前做拦截,对字节码做修改 可以在运行期对已加载类的字节码做变更,但是这种情况下会有很多的限制,后面会详细说 还有其他一些小众的功能 获取所有已经加载过的类 获取所有已经初始化过的类(执行过 clinit 方法,是上面的一个子集) 获取某个对象的大小 将某个...

郭传志的博客 1342

深入解析SAP ATP函数AVAILABILITY_CHECK_S4:从模拟到实战的销售订单可用性检查

本文深入解析SAP S/4HANA中的ATP函数AVAILABILITY_CHECK_S4,从参数配置到实战应用全面讲解销售订单可用性检查。通过详细代码示例和常见问题解决方案,帮助开发者掌握ATP检查的核心技术,提升供应链管理效率。

weixin_28331555的博客 332

自动化学报latex模板——ctex2.4.6和ctex2.9.2直接使用步骤

自动化学报latex模板——ctex2.4.6和ctex2.9.2直接使用步骤 1.背景及问题 最近在使用自动化学报latex模板写作业时,一只对latex搞不清楚,网上关于各种版本的latex下载了一堆(比如ctex中文套装方案的各个版本及texlive+texstudio方案,中间还升级了miktex,windet等),发现都未能成功编译出来自动化学报的latex模板,反正开始头很大!!!最后终于没忍住打开了: 自动化学报官网下载模板链接,因为我就要用latex模板(不能服输!)找到的解决方案是:使用

QIANFANGshiwo的博客 7715

【腹腔镜数据集】Cholec80+CholecSeg8k2020+Endoscapes2024

计算机辅助手术的发展旨在提高手术的正确性和安全性。然而,研究人员和工程师却面临着开发和训练更好算法所需的注释数据有限的问题。因此,同步定位与建图(SLAM)等基础算法的发展受到限制。基于Cholec80数据集,从Cholec80中的17个视频片段中提取了8,080个腹腔镜胆囊切除术图像帧,对图像进行注释并向公众发布。该数据集名为 CholecSeg8K。这些图像中的每一个都以十三个类别的像素级注释,这些类别通常在腹腔镜胆囊切除术中发现。

Toky_min的博客 2030

硬件测试之—纹波测试为什么不要使用接地夹子

示波器为什么不推荐使用接地夹

qq_19294353的博客 2993

最优化学习笔记1——关于拟牛顿法推导

从2020年3月份到现在,一年的时间里断断续续自学最优化,结合豆瓣读书、知乎等网站上的推荐,翻阅了以下书和课程: Stephen Boyd和Lieven Vandenberghe的《Convex Optimization》,这本书被公认为学习凸优化的必读经典著作,其中大量的篇幅讲应用,讲理论和算法的篇幅稍少一些。在B网站上有Boyd的视频课程,油管上也有,不过只有英文字幕,如果是零基础接触,直接看Boyd的视频稍显费劲,B站上也有凌青老师以《Convex Optimization》为教材的讲解,推荐作为入

xiaofei473的博客 1773

SLAM算法的优缺点

SLAM(Simultaneous Localization and Mapping,同时定位与地图构建)算法是一种通过传感器数据实时估计机器人自身位置和构建环境地图的技术。

selenia8860的博客 2909

【讯飞星火大模型AI】SpringBoot整合星火API:从零构建智能数据分析助手

本文详细介绍了如何使用SpringBoot框架整合讯飞星火大模型API,从零构建一个智能数据分析助手。通过清晰的步骤,指导开发者完成API密钥申请、项目搭建、SDK集成与核心代码编写,实现用户通过自然语言指令和CSV数据,即可自动获得ECharts图表代码与专业数据分析结论,极大降低数据分析与可视化的门槛。

neovim7hacker的博客 279

OPPO 数据分析面试题及参考答案

如何设计共享单车数据库的各个字段? 对于共享单车的数据库设计,首先考虑用户相关的字段。用户表可以包含用户 ID,这是一个唯一标识符,用于区分不同用户;姓名,记录用户的真实姓名;联系方式,比如手机号码,方便在出现问题时联系用户;注册时间,记录用户何时开始使用共享单车服务;信用分数,用于衡量用户使用共享单车过程中的行为是否合规,比如是否按时归还车辆等。 车辆信息表要有车辆 ID,这是车辆的唯一标识;车辆类型,例如普通单车、电动单车等;投放时间,即车辆投放到市场的时间;车辆状态,包括是否可用(如正

大模型大数据攻城狮的专栏 1186

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

上一篇: bytebuddy实现原理分析 &源码分析 (二)
下一篇: bytebuddy agentBuilder实用手册
舞动的痞老板
博客等级 码龄9年 99粉丝 150原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址