“지금까지”
로그 추적기라는 부가 기능을 클래스에 적용해왔고, 클래스 수 증가에 비례하여 프록시 클래스를 만들어야 하는 문제점이 있었다.
(이때 로그 추적을 위한 프록시 클래스의 소스 코드는 거의 같은 모양을 하고 있다)
자바가 기본 제공하는 JDK 동적 프록시나 CGLIB 같은 프록시 생성 오픈소스 기술을 활용하면 프록시 객체를 동적으로 만들어낼 수 있다.
(handler 만들고 동적 프록시 기술을 사용해서 프록시 객체를 찍어내면 된다)
JDK 동적 프록시 기술을 이해하기 위해서 먼저 리플렉션 기술을 학습한다
리플렉션 기술을 사용하면 클래스나 메서드의 메타 정보를 동적으로 획득하고, 코드도 동적으로 호출할 수 있다
예제
@Slf4j
static class Hello {
public String callA() {
log.info("callA");
return "A";
}
public String callB() {
log.info("callB");
return "B";
}
}
테스트 코드
@DisplayName("")
@Test
void reflection1() throws Exception {
// 클래스 정보
Class<?> clazz = Class.forName("hello.proxy.pureproxy.jdkdynamic.ReflectionTest$Hello");
Hello target = new Hello();
// callA 메서드 정보
Method methodCallA = clazz.getMethod("callA");
dynamicCall(methodCallA, target);
// callB 메서드 정보
Method methodCallB = clazz.getMethod("callB");
dynamicCall(methodCallB, target);
}
private void dynamicCall(Method method, Object target) throws Exception {
log.info("start");
Object result = method.invoke(target);
log.info("result={}", result);
}