Is it possible in Java to get class property value by its name? for example, i have class like
public class Test { private String field; public String getField() {...} public void setField() {...} }
and another class with Map
public class Main { private static final Map<String, Long> map = new HashMap<String, Long>(); static { map.put("field", new Long(1)); } public void doSth() { Set<String> keys = map.keySet(); Test t = new Test(); for (String key : keys) { //t.getPropertyValueByName(key); ? } }
You can use some of the Libraries that offer property-based access. I think the most known and used is beanutils. You can find one good example of the beanutils "in action" here. Some sample code:
A someBean = new A(); // access properties as Map Map<String, Object> properties = BeanUtils.describe(someBean); properties.set("name","Fred"); BeanUtils.populate(someBean, properties); // access individual properties String oldname = BeanUtils.getProperty(someBean,"name"); BeanUtils.setProperty(someBean,"name","Barny");
Yes. You can replace the commented out line with t.getClass().getField(map.get(key)).get(t). which will retrieve the value of the field on t.
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