簡體   English   中英

按字段名稱獲取對象引用

[英]Get object reference by field name

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字段(變量內部)的引用?

如何獲得innerf字段(變量內部)的引用?

你不需要它。 您只需要對包含它的對象的引用:在本例中, 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM