从HashMap中填充类属性

3
我希望将HashMap中的项目转换为类属性。有没有一种方法可以在不手动映射每个字段的情况下完成此操作?我知道使用Jackson可以将所有内容转换为JSON,然后再转回GetDashboard.class,这样属性就会被正确设置。但是这显然不是一个高效的方法。
数据:
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("workstationUuid", "asdfj32l4kjlkaslkdjflkj34");

分类:

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

1
如果一个类的属性不存在,应该如何处理? - durron597
1
反射是您唯一的解决方案。对于每个键,检查类是否具有与其名称相同的字段,然后将其值设置为哈希映射中的值。如果没有该字段,则跳过它。 - Sotirios Delimanolis
这取决于HashMap是如何被填充的,即在某些情况下使用Spring可能会起作用。 - durron597
2个回答

4
如果您想自己处理:
假设这个类:
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
    }
}

会打印(除非出现异常,您可以执行任何操作)

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

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接