按字段名称获取对象引用


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)的引用?

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

你不需要它。您只需要对包含它的对象的引用:在本例中,outerfields[i].get(this).参见 Javadoc。

好的,我在另一个答案被接受之前就开始了,但这里有一个完整的例子:

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;
    }
}

相关内容

  • 没有找到相关文章

最新更新