class SimpleInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("Before method: " + method.getName());
Object result = proxy.invokeSuper(obj, args);
System.out.println("After method: " + method.getName());
return result;
}
}
public class ByteBuddyExample {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Class<? extends SimpleClass> dynamicType = new ByteBuddy()
.subclass(SimpleClass.class)
.method(ElementMatchers.named("sayHello"))
.intercept(MethodDelegation.to(new SimpleInterceptor()))
.make()
.load(ByteBuddyExample.class.getClassLoader())
.getLoaded();
SimpleClass instance = dynamicType.newInstance();
instance.sayHello();
}
}
class SimpleClass {
public void sayHello() {
System.out.println("Hello world!");
}
}