I have an object that has a String field. I can obtain this field by calling:
Field field = someObj.getClass().getField(\"strField\");
I sett a
if you are using java.lang.reflect.Field, the "setter" is Field.set(Object,Object) and the "getter" is Field.get(Object). in both cases, the first parameter is the instance on which you want to access the field.
Even without the getter or the setter methods for a property, you can change or get the value using an object reference and Java Reflection.
import java.lang.reflect.Field;
public class Bean {
private String strField;
public static void main(String[] args) throws Exception {
Bean bean = new Bean();
Field field = bean.getClass().getDeclaredField("strField");
field.set(bean, "Hello");
System.out.println(field.get(bean));
}
}
Easiest way is to use BeanUtils:
String s = BeanUtils.getProperty(someObj, "strField");
Note that BeanUtils will attempt to convert your property into string. You need to have a getter and setter of the property