2014-04-07 4 views
0
public class Outer { 
    public Inner inner = new Inner(); 

    public void test() { 
     Field[] outerfields = this.getClass().getFields(); 
     for(Field outerf : outerfields) { 
      Field[] innerFields = outerfields[i].getType().getFields(); 
      for(Field innerf : innerFields) { 
        innerf.set(X, "TEST"); 
      } 
     } 
    } 

    public class Inner { 
     String foo; 
    }  
} 

X는 무엇이되어야합니까? 어떻게 innerf 필드 (변수 inner)의 참조를 얻을 수 있습니까?필드 이름으로 개체 참조 가져 오기

+0

더 많은 코드를 붙여 넣습니다. – RMachnik

+0

@JonK 테스트 샘플 일뿐입니다. 그러나 당신 말이 맞습니다. – alkis

+0

Ok는 편집을 마쳤습니다. 감사합니다. @JonK – alkis

답변

1

어떻게 innerf 필드 (변수 inner)의 참조를 얻을 수 있습니까?

필요하지 않습니다. 이 객체를 포함하는 객체에 대한 참조 만 필요합니다.이 경우 outerfields[i].get(this). Javadoc을 참조하십시오.

+0

대단히 감사합니다. 이것으로 완벽하게 해결되었습니다. – alkis

1

OK, 나는 다른 대답이 승인되기 전에이 작업을 시작했지만, 여기에 완벽한 예입니다

import java.lang.reflect.Field; 

public class Outer 
{ 
    public static void main(String[] args) throws Exception 
    { 
     Outer outer = new Outer(); 
     outer.test(); 

     System.out.println("Result: "+outer.inner.foo); 
    } 

    public Inner inner = new Inner(); 

    public void test() throws Exception 
    { 
     Field[] outerFields = this.getClass().getFields(); 
     for (Field outerField : outerFields) 
     { 
      Class<?> outerFieldType = outerField.getType(); 

      if (!outerFieldType.equals(Inner.class)) 
      { 
       // Don't know what to do here 
       continue; 
      } 

      Field[] innerFields = outerFieldType.getDeclaredFields(); 
      for (Field innerField : innerFields) 
      { 

       Class<?> innerFieldType = innerField.getType(); 
       if (!innerFieldType.equals(String.class)) 
       { 
        // Don't know what to do here 
        continue; 
       } 

       // This is the "public Inner inner = new Inner()" 
       // that we're looking for 
       Object outerFieldValue = outerField.get(this); 
       innerField.set(outerFieldValue, "TEST"); 
      } 
     } 
    } 

    public class Inner 
    { 
     String foo; 
    } 
} 
+0

마르코 감사합니다. 내 문제는 해결되지만 향후 참조 및 테스트를위한 완벽한 예를 제시하는 것이 좋습니다. 물론 upvoted. – alkis

관련 문제