Alex Rivera | Logout

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

Asked 2011-06-25T14:16:49.160
10

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?

Edit
Report

1 Answer

0

Should go like this:

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

Mind the exceptions.

answered 2011-06-25T14:27:15.293

Your Answer