public class UserClassService {
void join(User user) {
System.out.println("join = " + user);
}
void terminate(User user) {
System.out.println("terminate = " + user);
}
}
dependencies {
// https://mvnrepository.com/artifact/cglib/cglib
implementation 'cglib:cglib:3.3.0'
}
@Test
void cglib() {
MethodInterceptor handler = new MethodInterceptor() {
private final UserClassService userClassService = new UserClassService();
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
if (method.getName().equals("terminate")) {
System.out.println("proxy start");
Object invoke = method.invoke(userClassService, args);
System.out.println("proxy end");
return invoke;
}
return method.invoke(userClassService, args);
}
};
UserClassService userClassService = (UserClassService) Enhancer.create(UserClassService.class, handler);
userClassService.join(user);
userClassService.terminate(user);
//join = User@6f306067
//proxy start
//terminate = User@6f306067
//proxy end
}
2. byteBuddy library를 이용하는 방법
dependencies {
implementation 'net.bytebuddy:byte-buddy:1.14.0'
}
@Test
void byteBuddy() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<? extends UserClassService> proxyClass = new ByteBuddy()
.subclass(UserClassService.class)
.method(named("terminate"))
.intercept(InvocationHandlerAdapter.of(new InvocationHandler() {
UserClassService userClassService = new UserClassService();
@Override
public Object invoke(Object o, Method method, Object[] args) throws Throwable {
System.out.println("proxy start");
Object invoke = method.invoke(userClassService, args);
System.out.println("proxy end");
return invoke;
}
}))
.make()
.load(UserClassService.class.getClassLoader())
.getLoaded();
UserClassService userClassService = proxyClass.getConstructor(null).newInstance();
userClassService.join(user);
userClassService.terminate(user);
}
//1. final 로 상속을 막은 경우
//public final class UserClassService {
public class UserClassService {
//2. private 생성자로 상속을 막은 경우
//private UserClassService() { }
void join(User user) {
System.out.println("join = " + user);
}
void terminate(User user) {
System.out.println("terminate = " + user);
}
}