당신이 직접 수행 할 경우
클래스
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
을 (당신을 제외하고 원하는대로 할) 인쇄됩니다 다음 ? – durron597
반사가 유일한 해결책입니다. 각 키에 대해 클래스에 동일한 이름의 필드가 있는지 확인한 다음 해당 값을 해시 맵의 값으로 설정합니다. 필드가 없으면 건너 뜁니다. –
HashMap이 어떻게 채워지 는가에 달려 있습니다. 즉, Spring을 사용하는 것이 경우에 따라 작동 할 수 있습니다. – durron597