BookService bookService = (BookService) Proxy.newProxyInstance(BookService.class.getClassLoader(), new Class[]{BookService.class},
new InvocationHandler() {
BookService bookService = new DefaultBookService();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("rent")) {
System.out.println("before method call");
Object invoke = method.invoke(bookService, args);
System.out.println("after method call");
return invoke;
}
return method.invoke(bookService, args);
}
});
MethodInterceptor handler = new MethodInterceptor() {
BookService bookService = new BookService();
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("before method call");
return method.invoke(bookService, objects);
}
};
BookService bookService = (BookService) Enhancer.create(BookService.class, handler);
Class<? extends BookService> proxyClass = new ByteBuddy().subclass(BookService.class)
.method(named("rent"))
.intercept(InvocationHandlerAdapter.of(new InvocationHandler() {
BookService bookService = new BookService();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before method call");
return method.invoke(bookService, args);
}
}))
.make()
.load(BookService.class.getClassLoader())
.getLoaded();
BookService bookService = proxyClass.getConstructor(null).newInstance();