개발일기장

Proxy ... 본문

JAVA

Proxy ...

게슬 2023. 11. 26. 15:14
728x90

Proxy 사용법.

 

 

1. InvocationHandler를 구현한 객체를 만듬

생성자에 실제 method를 수행할 객체를 넣어줘야함.. 그리고 다른것도 넣어도 될듯..?

args에는 method를 호출 했을 때 넣어주는 인자값들.

@Slf4j
public class TimeInvocationHandler implements InvocationHandler {

    private final Object target;

    public TimeInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log.info("TimeProxy 실행");
        long startTime = System.currentTimeMillis();
        Object result = method.invoke(target, args);

        long endTime = System.currentTimeMillis();
        long resultTime = endTime - startTime;
        log.info("TimeProxy 종료 resultTime={}",resultTime);

        return result;
    }
}

 

2. Proxy를 생성해서 호출

        AInterface target = new AImpl();
        TimeInvocationHandler handler = new TimeInvocationHandler(target); // 위에서 구현한 객체

        AInterface proxy = (AInterface)Proxy.newProxyInstance(AInterface.class.getClassLoader(), // 실제 객체의 class loader
                new Class[]{AInterface.class},  // 실제 객체가 구현한 interface
                handler);  // handler
        String result = proxy.call("testMessage"); // 호출

 

이렇게 그냥 proxy로 만들어둔 method를 호출 하면 그 method만 수행하는게 아니라 proxy가 호출되어서 동작을함.

15:03:42.540 [main] INFO hello.proxy.jdkdynamic.code.TimeInvocationHandler - TimeProxy 실행
15:03:42.543 [main] INFO hello.proxy.jdkdynamic.code.TimeInvocationHandler - arg : testMessage
15:03:42.545 [main] INFO hello.proxy.jdkdynamic.code.AImpl - A 호출
15:03:42.550 [main] INFO hello.proxy.jdkdynamic.code.TimeInvocationHandler - TimeProxy 종료 resultTime=6

 

728x90
Comments