Java Reflection 관련

권장할 방법은 아니지만 어쩔수 없이 Java Reflection 을 사용할 일이 있어서 이래저래 자료를 찾아보았습니다. 찾아보다가 한가지 궁금한점이 생겼습니다. 상속과 overriding이 되었을 때에도 Java Reflection 이 제대로 동작하는가 였습니다. 어떤 인터넷 글에서 overriding 이 되더라도 Base 클래스의 Reflection 을 사용하면 Base 클래스의 메소드가 호출된다는 내용을 읽은것 같았습니다. 만약 그게 사실이라면 Java Reflection 을 사용할 수 없게 되버리는데 말이죠. (설마?) 그래서 간단한 Sample 을 작성해서 확인해보기로 하였습니다.  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.lang.reflect.Field;
import java.lang.reflect.Method;
 
 
public class ReflectionTest {
    public static class Base{
        protected int mFlag = 2;
         
        protected void print() {
            System.out.println("Base.Print");
        }
    }
     
    public static class Derived extends Base {
        public Derived() {
            mFlag = 3;
        }
        @Override
        protected void print() {
            System.out.println("Dervied.Print");
        }
    }
     
    public static void printWithReflection(Base base) {
        try {
            Field field = Base.class.getDeclaredField("mFlag");
            field.setAccessible(true);
            int flag = field.getInt(base);
            System.out.println(flag);
             
            Method method = Base.class.getDeclaredMethod("print", null);
            method.setAccessible(true);
            method.invoke(base, null);
        } catch (Exception e) {
        }
    }
     
    public static void main(String [] args) {
        Base base = new Base();
        Derived derived = new Derived();
         
        printWithReflection(base);
        printWithReflection(derived);
    }
}


위 코드에서 Derived 라는 클래스는 Base 클래스의 print 함수를 overriding 하였고, printWithReflection 함수는 Derived 클래스가 아닌 Base 클래스를 이용하여 Field 와 Method 를 받아서 호출하였습니다. 결과는 아래와 같이 overriding 하더라도 문제없이 동작하였습니다. 

2
Base.Print
3
Dervied.Print