简体   繁体   中英

Value of a field of Java object dynamically (by reflection)

I get names of various fields in a class like this :

Field[] f = MyClass.class.getDeclaredFields();
Sring str = f[0].toString();
MyClass cl = new MyClass();

Now I want to access the (public) field str from the object cl dynamically. How do I do that?

Use the Field.get method like this (for the 0th field):

Object x = f[0].get(cl);

To figure out which index the str field has you can do

int strIndex = 0;
while (!f[strIndex].getName().equals("str"))
    strIndex++;

Here's a full example illustrating it:

import java.lang.reflect.Field;

class MyClass {
    String f1;
    String str;
    String f2;
}

class Test {
    public static void main(String[] args) throws Exception {
        Field[] f = MyClass.class.getDeclaredFields();
        MyClass cl = new MyClass();
        cl.str = "hello world";

        int strIndex = 0;
        while (!f[strIndex].getName().equals("str"))
            strIndex++;

        System.out.println(f[strIndex].get(cl));

    }
}

Output:

hello world
Field f = Myclass.class.GetField("Str");
MyClass cl = new MyClass();
cl.Str = "Something";
String value = (String)f.get(cl); //value == "Something" 

Should go like this:

Field[] f = MyClass.class.getDeclaredFields();
MyClass targetObject = new MyClass();
...
Object fieldValue = f[interestingIndex].get(cl);

Mind the exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM