2014-06-24 15 views
0

내부 클래스 선언과 개인 속성이있는 클래스가 있습니다. Java reflection을 사용하여이 클래스를 실행하기 위해 main 함수에서 테스트 프로그램을 작성해야합니다. 여기JAVA 리플렉션을 사용하여 클래스를 실행하십시오.

public class Outter { 
private Inner in; 

public Outter(){ 
    in = new Inner(); 
} 

private class Inner{ 
    private void test(){ 
     System.out.println("test"); 
    } 
} 

은} 테스트 코드입니다 : 내 질문은 문 다음과 같습니다.

public class Test 
{ 
    public static void main(String[] args) throws Exception 
    { 
     // 1. How do i create a Class type for Inner class since its modifier 
     // is private, if I am going to need .setAccessible() then how do i 
     // use it? 
     Class outter1 = Outter.class; 

     // 2. How do I pass parameters of type Inner to the Class object? 
     Constructor con = outter1.getConstructor(new Class[]{int.class}); 

     // 3. Like this? 
     Field fields = outter1.getField("test"); 
     fields.setAccessible(true); 

     // 4. Well I am lost what is the logic route for me to follow when 
     // using java reflection to execute a class like this! 
     Object temp = outter1.newInstance(); 
     Outter outter = (Outter)temp; 
     System.out.println(fields.get(outter)); 
    } 
} 

답변

2

여기에 수행하려는 내용이 포함되어 있습니다.

코드는

try { 
    // gets the "in" field 
    Field f = Outer.class.getDeclaredField("in"); 
    // sets it accessible as it's private 
    f.setAccessible(true); 
    // gets an instance of the Inner class by getting the instance of the 
    // "in" field from an instance of the Outer class - we know "in" is 
    // initialized in the no-args constructor 
    Object o = Object o = f.get(Outer.class.newInstance()); 
    // gets the "execute" method 
    Method m = o.getClass().getDeclaredMethod("test", (Class<?>[])null); 
    // sets it accessible to this context 
    m.setAccessible(true); 
    // invokes the method 
    m.invoke(o, (Object[])null); 
} 
// TODO better handling 
catch (Throwable t) { 
    t.printStackTrace(); 
} 

클래스를 실행하는 ... (외부/내부)

public class Outer { 
    private Inner in; 
    public Outer() { 
     in = new Inner(); 
    } 
    private class Inner { 
     private void test() { 
      System.out.println("test"); 
     } 
    } 
} 

출력

test 
+0

코드가 정확하지만, (+1) 귀하의 답변에는 몇 가지 설명이 포함되어야한다고 생각합니다. 그렇지 않으면 OP는 그 차이를 이해하지 못하고 앞으로도 같은 실수를 저지를 것입니다. 귀하의 의견에 대해 – AlexR

+0

@AlexR에 감사드립니다. 내 코드에 주석을 달았습니다 ... 어떤 진술에서 내가 정교해야한다고 생각합니까? – Mena

+0

오, 죄송합니다. 코드 내부의 주석에 대해서는 신경을 쓰지 않았습니다. 같은 파일에서 내부 클래스와 2 클래스의 차이를 설명하는 것이 유용 할 것입니다. – AlexR

관련 문제