Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get property value by property name

Tags:

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); ?     }     } 
like image 466
kassie Avatar asked Aug 04 '13 16:08

kassie


Video Answer


2 Answers

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");  
like image 140
Dan94 Avatar answered Sep 20 '22 12:09

Dan94


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.

like image 31
bjc2406 Avatar answered Sep 20 '22 12:09

bjc2406