Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 993
mihsathe Avatar asked Jun 25 '11 14:06

mihsathe


2 Answers

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
like image 84
aioobe Avatar answered Oct 18 '22 22:10

aioobe


Field f = Myclass.class.GetField("Str");
MyClass cl = new MyClass();
cl.Str = "Something";
String value = (String)f.get(cl); //value == "Something" 
like image 4
Armen Tsirunyan Avatar answered Oct 18 '22 21:10

Armen Tsirunyan