<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.12.0</version>
</dependency>
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;
public class ByteBuddyExample {
public static void main(String[] args) throws Exception {
DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
.subclass(Object.class)
.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("Hello Byte Buddy!"))
.make();
Class<?> dynamicClass = dynamicType.load(ByteBuddyExample.class.getClassLoader())
.getLoaded();
Object dynamicObject = dynamicClass.getDeclaredConstructor().newInstance();
System.out.println(dynamicObject.toString());
}
}