如果你想自己做:
假设类
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