2013-04-24 122 views
2

我想将HashMap中的项目转换为类的属性。有没有办法做到这一点,而无需手动映射每个领域?我知道,与杰克逊我可以将所有东西都转换为JSON并返回到GetDashboard.class这将有正确的属性设置。这显然不是一个有效的方法来做到这一点。从HashMap填充类属性

数据:

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

类:

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

它应该如何,如果一个类的属性不存在处理? – durron597 2013-04-24 15:16:15

+1

反射是您唯一的解决方案。对于每个键,检查该类是否具有相同名称的字段,然后将其值设置为散列映射中的值。如果没有字段,请跳过它。 – 2013-04-24 15:16:44

+0

它取决于如何填充HashMap,即使用Spring可能在某些情况下工作 – durron597 2013-04-24 15:18:50

回答

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