Byte Buddy is a code generation and manipulation library for creating and modifying Java classes during the runtime of a Java application and without the help of a compiler. Other than the code generation utilities that ship with the Java Class Library, Byte Buddy allows the creation of arbitrary classes and is not limited to implementing interfaces for the creation of runtime proxies. Furthermore, Byte Buddy offers a convenient API for changing classes either manually, using a Java agent or during a build.
Byte Buddy就是一个可以在Java运行时动态生成java class的类库
存在的意义
对于一个工具的入门, 我们首先希望知道这个工具的出现是为了解决什么问题
据官方所言:
At first sight, runtime code generation can appear to be some sort of black magic that should be avoided and only few developers write applications that explicitly generate code during their runtime. However, this picture changes when creating libraries that need to interact with arbitrary code and types that are unknown at compile time. In this context, a library implementer must often choose between either requiring a user to implement library-proprietary interfaces or to generate code at runtime when the user’s types becomes first known to the library. Many known libraries such as for example Spring or Hibernate choose the latter approach which is popular among their users under the term of using Plain Old Java Objects. As a result, code generation has become an ubiquitous concept in the Java space. Byte Buddy is an attempt to innovate the runtime creation of Java types in order to provide a better tool set to those relying on code generation.
publicclassBar { // RuntimeType的作用: By declaring the @RuntimeType annotation on the method, Byte Buddy finally casts the returned value to the return value of the intercepted method if this is necessary. // In doing so, Byte Buddy also applies automatic boxing and unboxing. // 自动装箱和自动拆箱: 自动装箱调用valueOf将原始类型转换为对象, 拆箱调用intValue, doubleValue等将对象转换为原始类型
@RuntimeType public String sayHello() { return"The delegate will invoke this"; }
@RuntimeType publicstatic String sayHelloBar() { return"Hello this is bar"; }
java.lang.IllegalArgumentException: Cannot resolve ambiguous delegation of public java.lang.Integer NewFoo.custom() to net.bytebuddy.implementation.bind.MethodDelegationBinder$MethodBinding$Builder$Build@f535e794 or net.bytebuddy.implementation.bind.MethodDelegationBinder$MethodBinding$Builder$Build@c333a93f