通过反射,将map转换为java对象

已经知道对象的类型,以及属性对应的值,且值保存在map对象中,将该map转换为已知类型的对象。

方案:如代码。



[java]  view plain  copy
  1. 测试类:  
  2.     public static void main(String[] args) {  
  3.   
  4.         Map map = new HashMap<String,Object>();  
  5.         map.put("name""zhangsanfeng");  
  6.         map.put("sex""男");  
  7.         map.put("password""passwordInfo");  
  8.           
  9.         try {  
  10.             User user = (User) Utils.mapToBean(map, User.class);  
  11.             System.out.println(user.getName());  
  12.             System.out.println(user.getPassword());  
  13.             System.out.println(user.getSex());  
  14.         } catch (Exception e) {  
  15.             // TODO Auto-generated catch block  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19.       
  20.     user类:    
  21.     public class User {  
  22.   
  23.         private String name;  
  24.         private String sex;  
  25.         private String password;  
  26.         public String getName() {  
  27.             return name;  
  28.         }  
  29.         public void setName(String name) {  
  30.             this.name = name;  
  31.         }  
  32.         public String getSex() {  
  33.             return sex;  
  34.         }  
  35.         public void setSex(String sex) {  
  36.             this.sex = sex;  
  37.         }  
  38.         public String getPassword() {  
  39.             return password;  
  40.         }  
  41.         public void setPassword(String password) {  
  42.             this.password = password;  
  43.         }  
  44.     }  
  45.   
  46.   
  47.  /**  
  48.      * 将Map对象通过反射机制转换成Bean对象  
  49.      *   
  50.      * @param map 存放数据的map对象  
  51.      * @param clazz 待转换的class  
  52.      * @return 转换后的Bean对象  
  53.      * @throws Exception 异常  
  54.      */    
  55.     public static Object mapToBean(Map<String, Object> map, Class<?> clazz) throws Exception {    
  56.         Object obj = clazz.newInstance();    
  57.         if(map != null && map.size() > 0) {    
  58.             for(Map.Entry<String, Object> entry : map.entrySet()) {    
  59.                 String propertyName = entry.getKey();       //属性名  
  60.                 Object value = entry.getValue();    
  61.                 String setMethodName = "set"    
  62.                         + propertyName.substring(01).toUpperCase()  
  63.                         + propertyName.substring(1);    
  64.                 Field field = getClassField(clazz, propertyName);    
  65.                 if(field==null)  
  66.                     continue;  
  67.                 Class<?> fieldTypeClass = field.getType();    
  68.                 value = convertValType(value, fieldTypeClass);   
  69.                 try{  
  70.                     clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);   
  71.                 }catch(NoSuchMethodException e){  
  72.                     e.printStackTrace();  
  73.                 }  
  74.             }    
  75.         }    
  76.         return obj;    
  77.     }  
  78.       
  79.     /**  
  80.      * 获取指定字段名称查找在class中的对应的Field对象(包括查找父类)  
  81.      *   
  82.      * @param clazz 指定的class  
  83.      * @param fieldName 字段名称  
  84.      * @return Field对象  
  85.      */    
  86.     private static Field getClassField(Class<?> clazz, String fieldName) {    
  87.         if( Object.class.getName().equals(clazz.getName())) {    
  88.             return null;    
  89.         }    
  90.         Field []declaredFields = clazz.getDeclaredFields();    
  91.         for (Field field : declaredFields) {    
  92.             if (field.getName().equals(fieldName)) {    
  93.                 return field;    
  94.             }    
  95.         }    
  96.     
  97.         Class<?> superClass = clazz.getSuperclass();    
  98.         if(superClass != null) {// 简单的递归一下    
  99.             return getClassField(superClass, fieldName);    
  100.         }    
  101.         return null;    
  102.     }     
  103.       
  104.      /**  
  105.      * 将Object类型的值,转换成bean对象属性里对应的类型值  
  106.      *   
  107.      * @param value Object对象值  
  108.      * @param fieldTypeClass 属性的类型  
  109.      * @return 转换后的值  
  110.      */    
  111.     private static Object convertValType(Object value, Class<?> fieldTypeClass) {    
  112.         Object retVal = null;    
  113.         if(Long.class.getName().equals(fieldTypeClass.getName())    
  114.                 || long.class.getName().equals(fieldTypeClass.getName())) {    
  115.             retVal = Long.parseLong(value.toString());    
  116.         } else if(Integer.class.getName().equals(fieldTypeClass.getName())    
  117.                 || int.class.getName().equals(fieldTypeClass.getName())) {    
  118.             retVal = Integer.parseInt(value.toString());    
  119.         } else if(Float.class.getName().equals(fieldTypeClass.getName())    
  120.                 || float.class.getName().equals(fieldTypeClass.getName())) {    
  121.             retVal = Float.parseFloat(value.toString());    
  122.         } else if(Double.class.getName().equals(fieldTypeClass.getName())    
  123.                 || double.class.getName().equals(fieldTypeClass.getName())) {    
  124.             retVal = Double.parseDouble(value.toString());    
  125.         } else {    
  126.             retVal = value;    
  127.         }    
  128.         return retVal;    
  129.     }  

猜你喜欢

转载自blog.csdn.net/qq_36850813/article/details/80706532
今日推荐