我想将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;
答案 0 :(得分: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
答案 1 :(得分:1)
尝试Apache Commons BeanUtils http://commons.apache.org/proper/commons-beanutils/
BeanUtils.populate(Object bean, Map properties)