欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA中利用反射如何将map转为实体类,拿去不谢

程序员文章站 2022-04-15 23:08:51
// map转化为bean//2020/07/15public static T autoBeanToMap(Class clazz ,Map map)throws Exception{ if (map == null){ return null; } //得到class T obj = clazz.newInstance(); Field[] fields = obj.getClass().getDeclaredField....
// map转化为bean
//2020/07/15
public static <T>T autoBeanToMap(Class<T> clazz ,Map map)throws Exception{
   if (map == null){
      return null;
   }
   //得到class
   T obj = clazz.newInstance();
   Field[] fields = obj.getClass().getDeclaredFields();
   for (int i = 0; i < fields.length; i++) {
      try {
         //得到属性
         Field field = fields[i];
         //打开私有访问
         field.setAccessible(true);
         //获取属性
         String name = field.getName();
         if (map.containsKey(name)){
            if (null!=map.get(name)){
               field.set(obj,map.get(name).toString());
            }else{
               field.set(obj,"");
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
   return obj;
}

本文地址:https://blog.csdn.net/weixin_44152010/article/details/107359962