Spring 학습을 하다보면 reflection이라는 개념이 자주 나와 개념을 학습하기 위해 정리한 내용이다.
Spring 에서는 스프링 컨테이너에서 자바빈을 동적으로 생성할 때, 어노테이션을 통하여 자바 빈 객체여부를 판단한다.
e.g. 자바빈 여부를 판단할 수 있는 어노테이션이 적용된 예제소스
@Configuration
public class ExampleFactory() {
...
}
이때 자바빈을 동적으로 생성할 때 사용되는 것이 reflection 개념이다.
반영(reflection)은 컴퓨터 과학 용어로, 컴퓨터 프로그램에서 런타임 시점에 사용되는 자신의 구조와 행위를 관리(type introspection)하고 수정할 수 있는 프로세스를 의미한다. “type introspection”은 객체 지향 프로그램언어에서 런타임에 객체의 형(type)을 결정할 수 있는 능력을 의미한다.
출처: [반영 (컴퓨터 과학) - 위키백과, 우리 모두의 백과사전]
리플렉션은 컴퓨터 프로그램에서 런타임 시점에 사용되는 자신의 구조와 행위를 관리하고 수정할 수 있는 프로세스이다.
자바 프로그램은 컴파일러 기반 언어이다.
자바에서 reflection은 컴파일된 이후 런타임 환경에서 Reflection API를 통해 클래스, 인터페이스, 생성자, 메소드 그리고 필드를 동적으로 인스턴스를 생성, 검사할 수 있다.
Main.java
package me.devsign;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
// using Class.forName() method
Class c1 = Class.forName(args[0]);
getReflectionInfo(c1);
// using Object.getClass() method
Boo boo = new Boo();
Class c2 = boo.getClass();
getReflectionInfo(c2);
}
public static void getReflectionInfo(Class c) {
Method[] m = c.getDeclaredMethods();
Field[] f = c.getFields();
System.out.println("Class Name = " + c.getName());
for (Field field : f) {
System.out.println("field = " + field.getName());
}
for (Method method: m) {
System.out.println("method = " + method.getName());
}
}
}
Using Class.forName() method Output:
Class Name = me.devsign.Foo
method = getSomeLogic
method = getFooId
method = setFooId
method = getFooName
method = setFooName
Using Object.getClass() method Output:
Class Name = me.devsign.Boo
method = joinBoo
위의 예제는 두 가지 방법으로 특정 클래스에 대한 속성을 가져올 수 있다.
1. Class.forName()
2. Object.getClass()
추가적으로 속성 정보를 검색할 뿐만아니라, 실질적으로 속성을 변경하거나 메소드를 실행 시키는 등의 동작을 행할 수 있다.
조금 더 자세한 내용은 추후에 정리하여 올릴 계획이다.