1、方式一
/**
* 把Map转化为JavaBean
*/
public static <T> T map2bean(Map<String,Object> map, Class<T> clz) throws Exception{
T obj = clz.newInstance();
//从Map中获取和属性名称一样的值,把值设置给对象(setter方法)
BeanInfo b = Introspector.getBeanInfo(clz,Object.class);
PropertyDescriptor[] pds = b.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
//得到属性的setter方法
Method setter = pd.getWriteMethod();
//得到key名字和属性名字相同的value设置给属性
setter.invoke(obj, map.get(pd.getName()));
}
return obj;
}
2.方式2
/**
* map转换成Bean,只要Map键和JavaBean属性名一致即可,解决mapToBean因为单个首字母大写,映射找不到属性的问题
*/
public static <T, V> T mapToBeanByField(Map<String,V> map,Class<T> clz) throws Exception{
T obj = clz.newInstance();
Field field = null;
for(String key : map.keySet()) {
field = obj.getClass().getDeclaredField(key);
field.setAccessible(true);
field.set(obj, map.get(key));
}
return obj;
}
3.实体
/**
* @author qinxun
* @date 2023-06-02
* @Descripion: score实体
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ScoreBean implements Serializable {
private Long id;
private Double score;
}
4.测试
public static void main(String[] args) throws Exception {
Map<String,Object> map = new HashMap<>();
map.put("id",1L);
map.put("score",80.0);
ScoreBean scoreBean = map2bean(map, ScoreBean.class);
// 输出ScoreBean(id=1, score=80.0)
System.out.println(scoreBean);
}