2013-04-24 100 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