Java

Reflection

체리필터 2021. 6. 25. 10:14
728x90
반응형

리플렉션에 대해 정확하게 무엇이다라고 정의 내리기가 쉽지 않다.

명확하게 캡슐화를 하여 접근하지 못하도록 정의 된 생성자를 포함하여 멤버변수라던가 메소드에 접근 가능하도록 해 주는 기능이라고 정의하면 될려나 모르겠다.

원래는 접근하지 못하는 코드에 어떻게 접근하는 것일까? Reflection 이란 말 처럼 Heap 메모리에 올라간 Instance를 투영하여 실제 Class가 어떻게 생겼는지 확인하는 방법으로 접근한다고 한다. 내부적으로 정확하게 어떻게 구현 되어 있는지 알 수 없지만 ^^

그런데 이러한 기능은 코드를 통해 접근하지 못하도록 의도를 가지고 만든 코드를 오히려 망치는 기능일수도 있는데 왜 존재하는 것일까?

Reflection이 사용된 대표적인 코드는 바로 Spring Framework의 DI 부분이다.

보통 private 으로 생성된 instance에 @Autowired 어노테이션을 붙이면 자동으로 instance가 주입 되는데, 원칙상으로 private 이기 때문에 접근이 가능하면 안된다.

그런데 Spring은 어떻게 이 변수에 접근하여 instance를 주입할 수 있는 것일까? Spring 역시 바로 이 Reflection을 이용하여 Bean을 주입하게 된다.

관련된 소스를 한 번 따라가 보자. 사용 된 소스는 현재 개발중인 MSA 소스 중 Chauffeur 소스를 사용하였다.

@SpringBootApplication
@EnableScheduling
@EnableDiscoveryClient
@EnableFeignClients
public class ChauffeurApplication {
    public static void main(String[] args) {
        SpringApplication.run(ChauffeurApplication.class, args);
    }
}

 

위에서 실제 실행하는 부분은 SpringApplication.run 부분이다. 해당 부분으로 들어가 보면 다음과 같은 소스를 볼 수 있다.

package org.springframework.boot

...

	/**
	 * Static helper that can be used to run a {@link SpringApplication} from the
	 * specified source using default settings.
	 * @param primarySource the primary source to load
	 * @param args the application arguments (usually passed from a Java main method)
	 * @return the running {@link ApplicationContext}
	 */
	public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
		return run(new Class<?>[] { primarySource }, args);
	}

	/**
	 * Static helper that can be used to run a {@link SpringApplication} from the
	 * specified sources using default settings and user supplied arguments.
	 * @param primarySources the primary sources to load
	 * @param args the application arguments (usually passed from a Java main method)
	 * @return the running {@link ApplicationContext}
	 */
	public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
		return new SpringApplication(primarySources).run(args);
	}

 

첫 번째 run method가 호출 되고 그 이후 두 번째 run method가 호출 된다.

두 번째 method의 run 부분을 다시 따라 들어가면 아래와 같은 소스가 나온다.

	/**
	 * Run the Spring application, creating and refreshing a new
	 * {@link ApplicationContext}.
	 * @param args the application arguments (usually passed from a Java main method)
	 * @return a running {@link ApplicationContext}
	 */
	public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			listeners.started(context);
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}

		try {
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}
반응형

이 소스들 중에 Bean을 등록하는 부분으로 보이는 것이... 중간에 보이는 getSpringFactoriesInstances 메소드 인 듯 하다. 감으로 일단 찾아 들어가 보자.

	private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
		ClassLoader classLoader = getClassLoader();
		// Use names and ensure unique to protect against duplicates
		Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}

여기서 또 다시 createSpringFactoriesInstances를 이용하여 instance를 생성하는 것으로 보인다.

	private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
			ClassLoader classLoader, Object[] args, Set<String> names) {
		List<T> instances = new ArrayList<>(names.size());
		for (String name : names) {
			try {
				Class<?> instanceClass = ClassUtils.forName(name, classLoader);
				Assert.isAssignable(type, instanceClass);
				Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
				T instance = (T) BeanUtils.instantiateClass(constructor, args);
				instances.add(instance);
			}
			catch (Throwable ex) {
				throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
			}
		}
		return instances;
	}

해당 메소드에 들어가 보면 이제서야 Reflection을 이용하는 것을 볼 수 있다.

ClassUtil 클래스 안의 forName 이란 정적 메소드를 이요하는 것 같은데 정확하게 분석은 안해 보았지만 class를 얻어온 다음 getDeclaredConstructor와 같은 Reflection method를 사용하는 것을 볼 수 있다.

 

이와 같이 Runtime 시에 동적으로 DI 하기 위한 용도로 Reflection이 이용되는 것을 볼 수 있다.

또는 Test 코드 작성 시 private 변수에 접근하기 위해서 실제 로직에서 필요치 않은 setter를 만들지 않고 reflection을 이용하여 접근하여 사용할 수 있다.

다음 포스트에서는 실제 reflection code를 작성해 보도록 하겠다.

728x90
반응형