按字段名称获取对象引用

时间:2014-04-07 09:55:11

标签: java reflection

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应该是什么?如何获得内部字段(变量内部)的引用?

2 个答案:

答案 0 :(得分:1)

  

如何获取innerf字段(变量内部)的引用?

你不需要它。您只需要对包含它的对象的引用:在这种情况下,outerfields[i].get(this).请参阅Javadoc。

答案 1 :(得分:1)

好的,我在接受其他答案之前开始这个,但这是一个完整的例子:

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;
    }
}
相关问题