[ 이전 포스팅 요약 ]

Untitled

[ 리플렉션 ]

@Slf4j
public class ReflectionTest {
		@Test
		public void reflection2() throws Exception {
		    // 클래스의 메타정보 (내부 클래스는 구분을 위해 '$' 사용)
		    Class classHello = Class.forName("hello.proxy.jdkdynamic.ReflectionTest$Hello");
		
		    Hello target = new Hello();
				// callA 메서드 메타정보
		    Method methodCallA = classHello.getMethod("callA");
		    dynamicCall(methodCallA, target); // 찾은 클래스와 메서드의 메타정보를 넘겨준다.

				// callB 메서드 메타정보
		    Method methodCallB = classHello.getMethod("callB");
		    dynamicCall(methodCallB, target); // 찾은 클래스와 메서드의 메타정보를 넘겨준다.
		}
		
		/**
     * 공통 로직1, 공통 로직2를 한 번에 처리할 수 있는 통합된 공통 처리 로직
     * @param method 호출할 메서드 정보를 동적으로 제공
     * @param target 실제 실행할 인스턴스 정보
     * @throws Exception 호출할 클래스와 메서드 정보가 다르면 예외 발생
     */
		private void dynamicCall(Method method, Object target) throws Exception{
		    log.info("start"); // 공통 로직
		    Object result = method.invoke(target); // 동적으로 실제 객체 호출
		    log.info("result={}", result); // 공통 로직
		}
		
		@Slf4j
		static class Hello{
		    public String callA(){
		        log.info("callA");
		        return "A";
		    }
		
		    public String callB(){
		        log.info("callB");
		        return "B";
		    }
		}
}

[ JDK 동적 프록시 - 예제]