# bytebuddy-example **Repository Path**: laochen/bytebuddy-example ## Basic Information - **Project Name**: bytebuddy-example - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-11-05 - **Last Updated**: 2023-11-05 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # [byte-buddy字节码增强工具使用示例](https://juejin.cn/post/6917570505365012488) # [ByteBuddy入门教程](https://zhuanlan.zhihu.com/p/151843984) # [基于Byte-Buddy的AOP实践](https://zhuanlan.zhihu.com/p/352758133) # [ByteBuddy使用入坑](https://blog.csdn.net/m0_37556444/article/details/106695202) # [探针技术-JavaAgent 和字节码增强技术-Byte Buddy](https://segmentfault.com/a/1190000041998372) ``` Byte Buddy 动态增强代码总共有三种方式: subclass:对应 ByteBuddy.subclass() 方法。这种方式比较好理解,就是为目标类(即被增强的类)生成一个子类,在子类方法中插入动态代码。 rebasing:对应 ByteBuddy.rebasing() 方法。当使用 rebasing 方式增强一个类时,Byte Buddy 保存目标类中所有方法的实现,也就是说,当 Byte Buddy 遇到冲突的字段或方法时,会将原来的字段或方法实现复制到具有兼容签名的重新命名的私有方法中,而不会抛弃这些字段和方法实现。从而达到不丢失实现的目的。这些重命名的方法可以继续通过重命名后的名称进行调用。 redefinition:对应 ByteBuddy.redefine() 方法。当重定义一个类时,Byte Buddy 可以对一个已有的类添加属性和方法,或者删除已经存在的方法实现。如果使用其他的方法实现替换已经存在的方法实现,则原来存在的方法实现就会消失。 ``` # bytebuddy提供了一套ElementMatcher机制去匹配符合各种条件组合的方法(包括其他属性也是通过这套机制去匹配) ``` 1.匹配类中所有public方法 .method(ElementMatchers.isPublic()) 2.匹配名称为helloWorld且可见性为public的所有方法 .method(ElementMatchers.isPublic().and(ElementMatchers.named("helloWorld"))) 3.匹配名称为helloWorld且可见性为public但返回值类型不为String的所有方法 .method(ElementMatchers.isPublic().and(ElementMatchers.named("helloWorld")).and(ElementMatchers.not(ElementMatchers.returns(String.class)))) 4.匹配名称为helloWorld且第二个入参为String类型的所有方法 .method(ElementMatchers.isPublic().and(ElementMatchers.named("helloWorld")).and(ElementMatchers.takesArgument(1, String.class))) ``` # 重定义一个已经存在的类 ``` https://zhuanlan.zhihu.com/p/151843984 代码https://github.com/eugenp/tutorials/tree/master/libraries-5 虽然我们可以动态创建类,我们也可以操作已经加载的类。ByteBuddy可以重定义已经存在的类,然后使用ByteBuddyAgent将重定义的类重新加载到JVM中。 首先,让我们添加ByteBuddyAgent依赖到pom.xml: net.bytebuddy byte-buddy-agent 1.7.1 ByteBuddyAgent.install(); new ByteBuddy() .redefine(Foo.class) .method(named("sayHelloFoo")) .intercept(FixedValue.value("Hello Foo Redefined")) .make() .load( Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()); Foo f = new Foo(); assertEquals(f.sayHelloFoo(), "Hello Foo Redefined"); ``` # [Byte Buddy官方教程(三) — 字段和方法](https://blog.csdn.net/CaptHua/article/details/123195024) # TODO ``` 1. spring 动态注入bean ```