dev2016. 6. 8. 11:33

java 에서 reflection 을 이용해서 inner class (non-static nested class)의 객체를 생성하고자 할 때,

static nested class 와 달리 inner class 는 그냥 newInstance 만 해서는 객체 생성이 안된다.


왜 그럴까?

innerClass 는 outerClass 의 instance 내에서 생존하기 때문에, 

객체 생성을 위해선 outerClass 의 instance 가 필요하다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Outer {
 
    class Inner {
        int age = 10;
    }
 
    public static void main(String[] args) throws Exception {
        Constructor innerConstructor = Inner.class.getDeclaredConstructor(Outer.class);
        Object outerInstance = Outer.class.newInstance();
        Object newObject = innerConstructor.newInstance(outerInstance);
        Inner inner = (Inner)newObject;
        System.out.println(inner.age);
    }
} 
cs


참고

http://stackoverflow.com/questions/17485297/how-to-instantiate-inner-class-with-reflection-in-java

http://www.programmerinterview.com/index.php/java-questions/inner-vs-nested-classes/

http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class


'dev' 카테고리의 다른 글

oh my zsh  (0) 2016.08.17
linux 에서 파일 비교하기  (0) 2016.07.06
초보자를 위한 정규표현식  (0) 2016.06.03
태스크(Task) 실행과 스케줄링  (0) 2016.06.03
How To Acess Target Object Behind a Spring Proxy  (0) 2016.06.02