Java 从HashMap填充类属性
我想将HashMap中的项转换为类的属性。有没有一种方法可以在不手动映射每个字段的情况下执行此操作?我知道有了Jackson,我可以将所有内容转换为JSON并返回到属性设置正确的Java 从HashMap填充类属性,java,Java,我想将HashMap中的项转换为类的属性。有没有一种方法可以在不手动映射每个字段的情况下执行此操作?我知道有了Jackson,我可以将所有内容转换为JSON并返回到属性设置正确的GetDashboard.class。这显然不是一种有效的方法 数据: HashMap data=newhashmap(); 数据输入(“WorkstationUID”、“asdfj32l4kjlkaslkdjflkj34”); 类别: public class GetDashboard implements Even
GetDashboard.class
。这显然不是一种有效的方法
数据:
HashMap data=newhashmap();
数据输入(“WorkstationUID”、“asdfj32l4kjlkaslkdjflkj34”);
类别:
public class GetDashboard implements EventHandler<Dashboard> {
public String workstationUuid;
公共类GetDashboard实现EventHandler{
公共字符串workstationuid;
试试Apache Commons BeanUtils
BeanUtils.populate(对象bean、映射属性)
如果您想自己动手:
上课
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
}
}
如果类的属性不存在,它应该如何处理?反射是唯一的解决方案。对于每个键,检查类是否有同名字段,然后将其值设置为hashmap中的值。如果没有字段,则跳过它。这取决于hashmap的填充方式,即在某些情况下使用Spring可能会起作用
// 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