I am trying to convert Cglib proxy to ByteBuddy. Cglib has net.sf.cglib.proxy.Proxy interface to intercept all method calls. I check the documentation of ByteBuddy but couldnt find such an example. Without such interface for every object that i instantiate with ByteBuddy i am repeating same thing again and agin. Is there a better way to do this with ByteBuddy?
Here is my example code snippet:
Service:
public class MyService {
public void sayFoo() {
System.out.println("foo");
}
public void sayBar() {
System.out.println("bar");
}
}
Interceptor:
public class MyServiceInterceptor {
public void sayFoo(@SuperCall Callable<Void> zuper) {
try {
zuper.call();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sayBar(@SuperCall Callable<Void> zuper) {
try {
zuper.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Test:
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.dynamic.ClassLoadingStrategy;
import net.bytebuddy.instrumentation.MethodDelegation;
import net.bytebuddy.instrumentation.method.matcher.MethodMatchers;
public class Main {
public static void main(String[] args) throws Exception {
ByteBuddy buddy = new ByteBuddy(ClassFileVersion.forCurrentJavaVersion());
Class<? extends MyService> serviceClass =
buddy.subclass(MyService.class)
.method(MethodMatchers.named("sayFoo").or(MethodMatchers.named("sayBar")))
.intercept(MethodDelegation.to(new MyServiceInterceptor()))
.make()
.load(Main.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
MyService service = serviceClass.newInstance();
service.sayFoo();
service.sayBar();
}
}