我有一个 HashMap 对象列表,其中 hashMap 对象包含属性名称作为键,属性值作为值列表>。如何将这些 HashMap 对象中的每一个转换为我的 POJO 类的对象??
最佳答案
以下是如何使用reflection来做到这一点:
Pojo 类:
public class MyPojo {
private String text;
private Integer number;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
使用反射填充 pojo 实例;
final List<Map<String, Object>> objects = new ArrayList<Map<String, Object>>();
objects.add(new HashMap<String, Object>());
objects.get(0).put("text", "This is my text value.");
objects.get(0).put("number", 10);
objects.add(new HashMap<String, Object>());
objects.get(1).put("text", "This is my second text value.");
objects.get(1).put("number", 20);
ArrayList<MyPojo> pojos = new ArrayList<MyPojo>();
for (Map<String, Object> objectMap : objects) {
MyPojo pojo = new MyPojo();
for (Entry<String, Object> property : objectMap.entrySet()) {
Method setter = MyPojo.class.getMethod("set" + property.getKey().substring(0, 1).toUpperCase()
+ property.getKey().substring(1), property.getValue().getClass());
setter.invoke(pojo, property.getValue());
}
pojos.add(pojo);
}
for (MyPojo pojo : pojos) {
System.out.println(pojo.getText() + " " + pojo.getNumber());
}
输出:
This is my text value. 10
This is my second text value. 20
关于java - 将 list<map<string,object>> 转换为 POJO 类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28496684/