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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With