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. https://bytebuddy.net/#/
Byte Buddy 是一个代码生成和操作库,用于在 Java 应用程序运行时创建和修改 Java 类,而无需编译器的帮助。
举个栗子
package cn.live;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.core.Is.*;
import org.junit.Test;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;
public class ByteBuddyTest {
@Test
public void test1() throws InstantiationException, IllegalAccessException {
Class<?> dynamicType = new ByteBuddy()
.subclass(Object.class)
.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("Hello World!"))
.make()
.load(ByteBuddy.class.getClassLoader())
.getLoaded();
System.out.println(dynamicType.newInstance().toString());
assertThat(dynamicType.newInstance().toString(), is("Hello World!"));
}
}
生成 Object 类的子类,拦截该子类的 toString() 方法,并返回固定的字符串 Hello World!。
执行结果:
Hello World!
方法详解:
基础 API
总结
Byte Buddy 是一个轻量级的运行时类生成工具。生成的类不会产生字节码文件,就像它的 Logo 幽灵一样,存在于 Java 应用程序之中。
PS. 似乎,可以使用 Byte Buddy 干一些奇奇怪怪的事情哟~