Reflection in Java is a subject as old as Java itself, and likewise is the kind of thing that you can easily forget the details after some time without dealing with it. For example, to get a field from a given class, a call to getClass().getField(fieldName) will do the job, but only if the field is not private, which then you should use getDeclaredField() and call setAccessible(true). But again, only if such field is declared in the same class you are querying – e.g, it does not apply to the super class.
The list goes on and on.
There are many libraries out there, from the very low level to the high level. One good example of the latter is ReflectUtils, a very convenient and easy utility class.
- Getting a value from an object field
Object value = ReflectUtils.getInstance().getFieldValue(someInstance, "fieldName");
- Setting a value on an object field
TestEntity thing = new TestEntity(); ReflectUtils.getInstance().setFieldValue(thing, "entityId", 33); // value of thing.getEntityId() will be "33", value is autoconverted into the right type
- Setting a nested value on an object field
Object thing = new HashMap(); // using a hashmap for simplicity here, could easily be nested POJOs ReflectUtils.getInstance().setFieldValue(thing, "person.contactInfo.name", "aaronz"); // the value of the name field which is on the object in the contactInfo field which is on the object in the person field on the thing object is set to "aaronz"
The library is available at http://code.google.com/p/reflectutils/