国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費(fèi)電子書(shū)等14項(xiàng)超值服

開(kāi)通VIP
重載copyProperties,使其支持Map類(lèi)型

    最近,項(xiàng)目組要用到一個(gè)功能,就是用BeanUtils.copyProperties復(fù)制一個(gè)Map里的屬性值到另外一個(gè)對(duì)象。

    BeanUtils和PropertyUtils類(lèi)是許多開(kāi)源框架中頻繁使用的兩個(gè)工具,它們都能實(shí)現(xiàn)將一個(gè)類(lèi)中的屬性拷貝到另一個(gè)類(lèi)中,這個(gè)功能甚至是spring實(shí)現(xiàn)依賴(lài)注入的基礎(chǔ)。研究一下apache的comon包中如何實(shí)現(xiàn)這個(gè)兩個(gè)工具,可以發(fā)現(xiàn)它們都是使用java.lang.reflect和java.beans這兩個(gè)包下的幾個(gè)類(lèi)來(lái)實(shí)現(xiàn)的。

    但是BeanUtils.copyProperties只支持兩個(gè)對(duì)象之間的復(fù)制,其原理:是利用反射讀取到第一個(gè)對(duì)象(源類(lèi))的所有屬性,然后對(duì)這些屬性集合進(jìn)行for循環(huán),再在for循環(huán)里面判斷這些屬性是否有set方法,有則再對(duì)第二個(gè)對(duì)象(目標(biāo)類(lèi))進(jìn)行循環(huán)取出屬性一一對(duì)比,相等則調(diào)用目標(biāo)類(lèi)的set方法得到源類(lèi)的get方法得到的值。

    改后主要就是兩點(diǎn):第一:源類(lèi)(Map類(lèi)型)的Key作為屬性和目標(biāo)類(lèi)的屬性對(duì)比,相等則取出此Key的Value賦給目標(biāo)類(lèi)(當(dāng)然還是用目標(biāo)類(lèi)此屬性的set方法)。注意:如果是頁(yè)面得到的getParameterMap()這樣的Map,其值是一個(gè)數(shù)組,一般只需要取第0項(xiàng)就可以了。

源代碼:

  1. /** 實(shí)現(xiàn)將源類(lèi)屬性拷貝到目標(biāo)類(lèi)中
  2.        * @param source 
  3.        * @param target
  4.        */
  5.     public static void copyProperties(Object source, Object target) {
  6.         try {
  7.             // 獲取目標(biāo)類(lèi)的屬性信息
  8.             BeanInfo targetbean = Introspector.getBeanInfo(target.getClass());
  9.             PropertyDescriptor[] propertyDescriptors = targetbean
  10.                     .getPropertyDescriptors();
  11.             // 對(duì)每個(gè)目標(biāo)類(lèi)的屬性查找set方法,并進(jìn)行處理
  12.             for (int i = 0; i < propertyDescriptors.length; i++) {
  13.                 PropertyDescriptor pro = propertyDescriptors[i];
  14.                 Method wm = pro.getWriteMethod();
  15.                 if (wm != null) {// 當(dāng)目標(biāo)類(lèi)的屬性具有set方法時(shí),查找源類(lèi)中是否有相同屬性的get方法
  16.                     BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass());
  17.                     PropertyDescriptor[] sourcepds = sourceBean.getPropertyDescriptors();
  18.                     for (int j = 0; j < sourcepds.length; j++) {
  19.                         if (sourcepds[j].getName().equals(pro.getName())) { // 匹配
  20.                             Method rm = sourcepds[j].getReadMethod();
  21.                             // 如果方法不可訪問(wèn)(get方法是私有的或不可達(dá)),則拋出SecurityException
  22.                             if (!Modifier.isPublic(rm.getDeclaringClass().getModifiers())) {
  23.                                 rm.setAccessible(true);
  24.                             }
  25.                             // 獲取對(duì)應(yīng)屬性get所得到的值
  26.                             Object value = rm.invoke(source, new Object[0]);
  27.                             if (!Modifier.isPublic(wm.getDeclaringClass().getModifiers())) {
  28.                                 wm.setAccessible(true);
  29.                             }
  30.                             // 調(diào)用目標(biāo)類(lèi)對(duì)應(yīng)屬性的set方法對(duì)該屬性進(jìn)行填充
  31.                             wm.invoke((Object) target, new Object[] { value });
  32.                             break;
  33.                         }
  34.                     }
  35.                 }
  36.             }
  37.         } catch (IntrospectionException e) {
  38.             e.printStackTrace();
  39.         } catch (IllegalArgumentException e) {
  40.             e.printStackTrace();
  41.         } catch (IllegalAccessException e) {
  42.             e.printStackTrace();
  43.         } catch (InvocationTargetException e) {
  44.             e.printStackTrace();
  45.         }
  46.     }

修改后支持Map的代碼:

  1. /**
  2.      * 實(shí)現(xiàn)將源類(lèi)屬性拷貝到目標(biāo)類(lèi)中
  3.      * 
  4.      * @param Map map
  5.      * @param Object obj
  6.      */
  7.     public static void copyProperties(Map map, Object obj) throws Exception {
  8.         // 獲取目標(biāo)類(lèi)的屬性信息
  9.         BeanInfo targetbean = Introspector.getBeanInfo(obj.getClass());
  10.         PropertyDescriptor[] propertyDescriptors = targetbean.getPropertyDescriptors();
  11.         // 對(duì)每個(gè)目標(biāo)類(lèi)的屬性查找set方法,并進(jìn)行處理
  12.         for (int i = 0; i < propertyDescriptors.length; i++) {
  13.             PropertyDescriptor pro = propertyDescriptors[i];
  14.             Method wm = pro.getWriteMethod();
  15.             if (wm != null) {// 當(dāng)目標(biāo)類(lèi)的屬性具有set方法時(shí),查找源類(lèi)中是否有相同屬性的get方法
  16.                 Iterator ite = map.keySet().iterator();
  17.                 while (ite.hasNext()) {
  18.                     String key = (String) ite.next();
  19.                     // 判斷匹配
  20.                     if (key.equals(pro.getName())) {
  21.                         if (!Modifier.isPublic(wm.getDeclaringClass().getModifiers())) {
  22.                             wm.setAccessible(true);
  23.                         }
  24.                         Object value = ((String[]) map.get(key))[0];
  25.                         // 調(diào)用目標(biāo)類(lèi)對(duì)應(yīng)屬性的set方法對(duì)該屬性進(jìn)行填充
  26.                         wm.invoke((Object) obj, new Object[] { value });
  27.                         break;
  28.                     }
  29.                 }
  30.             }
  31.         }
  32.     }

上次寫(xiě)的那個(gè)方法只適用于String類(lèi)型。今天擴(kuò)展了一下,寫(xiě)成了一個(gè)類(lèi),支持int/Integer、Date和自定義對(duì)象。

  1. import java.beans.BeanInfo;
  2. import java.beans.Introspector;
  3. import java.beans.PropertyDescriptor;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.lang.reflect.Method;
  6. import java.lang.reflect.Modifier;
  7. import java.text.ParseException;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Date;
  10. import java.util.Iterator;
  11. import java.util.Map;
  12. public class BeanUtils {
  13.     public static String DATE_FORMAT = "yyyy-MM-dd";
  14.     public static String[] TYPE_SIMPLE = {"java.lang.Integer","int","java.util.Date"};
  15.     public static String TYPE_INTEGER = "java.lang.Integer,int";
  16.     public static String TYPE_DATE = "java.util.Date";
  17.     
  18.     /**
  19.      * 得到空格之后的字符
  20.      * 
  21.      * @param String type
  22.      * @param String str
  23.      * @return Date
  24.      * @throws ParseException
  25.      */
  26.     public static String splitSpace(String str) throws ParseException{
  27.         if(str.contains(" ")){
  28.             return str.split(" ")[1];
  29.         } else {
  30.             return str;
  31.         }
  32.     }
  33.     
  34.     /**
  35.      * 判斷是否是簡(jiǎn)單數(shù)據(jù)類(lèi)型
  36.      * 
  37.      * @param String type
  38.      */
  39.     public static boolean isSimpleType(String type) {
  40.         for (int i = 0; i < TYPE_SIMPLE.length; i++) {
  41.             if (type.equals(TYPE_SIMPLE[i])) {
  42.                 return true;
  43.             }
  44.         }
  45.         return false;
  46.     }
  47.     /**
  48.      * 把String類(lèi)型轉(zhuǎn)換為Integer
  49.      * 
  50.      * @param String str
  51.      * @return Integer
  52.      */
  53.     public static Integer parseInteger(String str){
  54.         if(str == null || str.equals("")){
  55.             return 0;
  56.         } else {
  57.             return Integer.parseInt(str);
  58.         }
  59.     }
  60.     
  61.     /**
  62.      * 把String類(lèi)型轉(zhuǎn)換為Date
  63.      * 
  64.      * @param String str
  65.      * @return Date
  66.      * @throws ParseException
  67.      */
  68.     public static Date parseDate(String str) throws ParseException{
  69.         if(str == null || str.equals("")){
  70.             return null;
  71.         } else {
  72.             SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
  73.             Date date = sdf.parse(str);
  74.             return date;
  75.         }
  76.     }
  77.     
  78.     /**
  79.      * 轉(zhuǎn)換對(duì)象(用戶定義的對(duì)象)。設(shè)置對(duì)象的Id。
  80.      * 
  81.      * @param Class clazz
  82.      * @param  String str
  83.      * @return Object
  84.      * @throws IllegalAccessException 
  85.      * @throws InstantiationException 
  86.      * @throws NoSuchMethodException 
  87.      * @throws SecurityException 
  88.      * @throws InvocationTargetException 
  89.      * @throws IllegalArgumentException 
  90.      * @throws ParseException
  91.      */
  92.     public static Object parseObject(Class clazz, String str) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
  93.         Object obj;
  94.         if(str == null || str.equals("")){
  95.             obj = null;
  96.         } else {
  97.             obj = clazz.newInstance();
  98.             Method m = clazz.getMethod("setId",str.getClass());
  99.             m.invoke(obj,str);
  100.         }
  101.         return obj;
  102.     }
  103.     
  104.     /**
  105.      * 根據(jù)類(lèi)型進(jìn)行轉(zhuǎn)換
  106.      * 
  107.      * @param Class clazz
  108.      * @param String str
  109.      * @return Object
  110.      * @throws ParseException
  111.      * @throws IllegalAccessException 
  112.      * @throws InstantiationException 
  113.      * @throws InvocationTargetException 
  114.      * @throws NoSuchMethodException 
  115.      * @throws IllegalArgumentException 
  116.      * @throws SecurityException 
  117.      */
  118.     public static Object parseByType(Class clazz, String str) throws ParseException, InstantiationException, IllegalAccessException, SecurityException, IllegalArgumentException, NoSuchMethodException, InvocationTargetException{
  119.         Object r = "";
  120.         String clazzName = splitSpace(clazz.getName());
  121.         if (isSimpleType(clazzName)){
  122.             if (TYPE_INTEGER.contains(clazzName)) {
  123.                 r = parseInteger(str);
  124.             } else if (TYPE_DATE.contains(clazzName)) {
  125.                 r = parseDate(str);
  126.             }
  127.         } else {
  128.             r = parseObject(clazz, str);
  129.         }
  130.         return r;
  131.     }
  132.     
  133.     /** 實(shí)現(xiàn)將源類(lèi)(Map類(lèi)型)屬性拷貝到目標(biāo)類(lèi)中
  134.        * @param Map map 
  135.        * @param Object obj
  136.        */
  137.     public static void copyProperties(Map map, Object obj) throws Exception {
  138.         // 獲取目標(biāo)類(lèi)的屬性信息
  139.         BeanInfo targetbean = Introspector.getBeanInfo(obj.getClass());
  140.         PropertyDescriptor[] propertyDescriptors = targetbean.getPropertyDescriptors();
  141.         // 對(duì)每個(gè)目標(biāo)類(lèi)的屬性查找set方法,并進(jìn)行處理
  142.         for (int i = 0; i < propertyDescriptors.length; i++) {
  143.             PropertyDescriptor pro = propertyDescriptors[i];
  144.             Method wm = pro.getWriteMethod();
  145.             if (wm != null) {
  146.                 Iterator ite = map.keySet().iterator();
  147.                 while (ite.hasNext()) {
  148.                     String key = (String) ite.next();
  149.                     // 判斷匹配
  150.                     if (key.toLowerCase().equals(pro.getName().toLowerCase())) {
  151.                         if (!Modifier.isPublic(wm.getDeclaringClass().getModifiers())) {
  152.                             wm.setAccessible(true);
  153.                         }
  154.                         Object value = ((String[]) map.get(key))[0];
  155.                         String pt = splitSpace(pro.getPropertyType().getName());
  156.                         //判斷類(lèi)型是否匹配,不匹配則作強(qiáng)制轉(zhuǎn)換
  157.                         if (!(pt.equals(value.getClass().getName()))) {
  158.                             value = parseByType(pro.getPropertyType(),value.toString());
  159.                         }
  160.                         // 調(diào)用目標(biāo)類(lèi)對(duì)應(yīng)屬性的set方法對(duì)該屬性進(jìn)行填充
  161.                         wm.invoke((Object) obj, new Object[] {value});
  162.                         break;
  163.                     }
  164.                 }
  165.             }
  166.         }
  167.     }
  168. }
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
Mybatis返回Map的一種實(shí)現(xiàn)
學(xué)習(xí):java原理
金融記數(shù)法 普通數(shù)字 相互轉(zhuǎn)換
【Java】Converter(數(shù)據(jù)類(lèi)型轉(zhuǎn)換工具類(lèi))
==和equals
java筆記.equals的方法
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服