2013-04-24 3 views
2

HashMap의 항목을 클래스의 속성으로 변환하려고합니다. 각 필드를 수동으로 매핑하지 않고이 작업을 수행 할 수있는 방법이 있습니까? 나는 Jackson과 함께 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

+1

반사가 유일한 해결책입니다. 각 키에 대해 클래스에 동일한 이름의 필드가 있는지 확인한 다음 해당 값을 해시 맵의 값으로 설정합니다. 필드가 없으면 건너 뜁니다. –

+0

HashMap이 어떻게 채워지 는가에 달려 있습니다. 즉, Spring을 사용하는 것이 경우에 따라 작동 할 수 있습니다. – durron597

답변

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