<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.11.13</version>
</dependency>
public class Foo {
public void bar() {
System.out.println("Hello, Byte Buddy Agent!");
}
}
public class LogInterceptor {
@RuntimeType
public static Object intercept(@This Object obj) {
System.out.println("Before method call: " + obj.getClass().getName());
try {
return ((Callable<?>) obj).call();
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
System.out.println("After method call: " + obj.getClass().getName());
}
}
}
public class FooInterceptor {
public static void main(String[] args) throws Exception {
Foo foo = new ByteBuddy()
.subclass(Foo.class)
.method(named("bar"))
.intercept(MethodDelegation.to(LogInterceptor.class))
.make()
.load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.getDeclaredConstructor()
.newInstance();
foo.bar();
}
}
Before method call: com.example.Foo
Hello, Byte Buddy Agent!
After method call: com.example.Foo