直接上代码
@Test
public void test19() throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
map.put("id", 1L);
map.put("name", "Java编程思想");
map.put("author", "张三");
map.put("infor" , "test");
Book b = new Book();
copyMapToObject(map, b);
System.out.println(b); // Book{id=1, name='Java编程思想', author='张三'}
}
Book.java
public class Book {
private long id;
private String name;
private String author;
public Book() {
}
// 省略getter/setter
}
工具类
// copy Map中的属性 到 实体类中
public static void copyMapToObject(Map<String, Object> map, Object o) {
Set<String> set = map.keySet();
Class c = o.getClass();
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
if (set.contains(f.getName())){
try {
f.set(o, map.get(f.getName()));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}