3

我想将 HashMap 中的项目转换为类的属性。有没有办法在不手动映射每个字段的情况下做到这一点?我知道使用 Jackson,我可以将所有内容转换为 JSON,然后再转换为GetDashboard.class正确设置属性的 JSON。这显然不是一种有效的方法。

数据:

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

班级:

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

2 回答 2

4

如果你想自己做:

假设类

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

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

以下

// 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
    }
}

将打印(做任何你想做的事,除了)

java.lang.NoSuchFieldException: asdas
    at java.lang.Class.getDeclaredField(Unknown Source)
    at testing.Main.main(Main.java:100)
workstationUuid: asdfj32l4kjlkaslkdjflkj34, id: 123
于 2013-04-24T15:25:26.200 回答
2

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

BeanUtils.populate(Object bean, Map properties)

于 2013-04-24T15:23:05.587 回答