Ben
Ben

Reputation: 62364

Populate class properties from HashMap

I want to convert items in a HashMap to properties of a class. Is there a way to do this without manually mapping each field? I know that with Jackson I could convert everything to JSON and back to GetDashboard.class which would have the properties set correctly. That's clearly not an efficient way to do this.

Data:

HashMap<String, Object> data = new HashMap<String, Object>();
data.put("workstationUuid", "asdfj32l4kjlkaslkdjflkj34");

Class:

public class GetDashboard implements EventHandler<Dashboard> {
    public String workstationUuid;

Upvotes: 3

Views: 2257

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

If you want to do it yourself:

Assuming the class

public class GetDashboard {
    private String workstationUuid;
    private int id;

    public String toString() {
        return "workstationUuid: " + workstationUuid + ", id: " + id;
    }
}

The following

// populate your map
HashMap<String, Object> data = new HashMap<String, Object>(); 
data.put("workstationUuid", "asdfj32l4kjlkaslkdjflkj34");
data.put("id", 123);
data.put("asdas", "Asdasd"); // this field does not appear in your class

Class<?> clazz = GetDashboard.class;
GetDashboard dashboard = new GetDashboard();
for (Entry<String, Object> entry : data.entrySet()) {
    try {
        Field field = clazz.getDeclaredField(entry.getKey()); //get the field by name
        if (field != null) {
            field.setAccessible(true); // for private fields
            field.set(dashboard, entry.getValue()); // set the field's value for your object
        }
    } catch (NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
        // handle
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        // handle
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        // handle
    }
}

Will print (do whatever you want with the exception)

java.lang.NoSuchFieldException: asdas
    at java.lang.Class.getDeclaredField(Unknown Source)
    at testing.Main.main(Main.java:100)
workstationUuid: asdfj32l4kjlkaslkdjflkj34, id: 123

Upvotes: 4

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

try Apache Commons BeanUtils http://commons.apache.org/proper/commons-beanutils/

BeanUtils.populate(Object bean, Map properties)

Upvotes: 3

Related Questions