리플렉션(reflection)이란?
Object 클래스와 GetType메소드
Object는 모든 데이터 형식의 조상이다. 그러므로 모든 데이터 형식은 Object형식이 가지고 있는 다음 메서드들을 모두 가지고 있다.
위 5개의 메서드중 GetType() 메서드는 객체의 Type 정보를 반환하는 메서드이다.
Pokemon형식의 type을 가져오는 예제 코드이다.
static void Main(string[] args)
{
Pokemon pokemon = new Pokemon();
Type type = pokemon.GetType();
Console.WriteLine(type);
}
Type은 타입, 어셈블리 이름, 프로퍼티, 메소드, 이벤트,필드등의 데이터 타입에 관한 모든 정보를 가지고 있다. 그렇기 때문에 Type을 이용한 리플렉션이 가능한 것이다.
Type type = pokemon.GetType();
// public 인스턴스 필드 가져오기
FieldInfo[] fields1 = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
// public이 아닌 인스턴스 필드 가져오기
FieldInfo[] fields2 = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
// public 스태틱 필드 가져오기
FieldInfo[] fields3 = type.GetFields(BindingFlags.Public | BindingFlags.Static);
// public이 아닌 스태틱 필드 가져오기
FieldInfo[] fields4 = type.GetFields(BindingFlags.NonPublic | BindingFlags.Static);