##### Coverage Report - com.ctrip.apollo.common.utils.BeanUtils

Classes in this File | Line Coverage | Branch Coverage | Complexity
BeanUtils |
0% | 0/98
0% | 0/38
| 4.545454545454546;4.545

1 |  |
     package com.ctrip.apollo.common.utils;
2 |  |
3 |  |
     import java.beans.PropertyDescriptor;
4 |  |
     import java.lang.reflect.Field;
5 |  |
     import java.util.ArrayList;
6 |  |
     import java.util.Collections;
7 |  |
     import java.util.HashMap;
8 |  |
     import java.util.HashSet;
9 |  |
     import java.util.List;
10 |  |
     import java.util.Map;
11 |  |
     import java.util.Set;
12 |  |
13 |  |
     import org.springframework.beans.BeanWrapper;
14 |  |
     import org.springframework.beans.BeanWrapperImpl;
15 |  |
     import org.springframework.util.CollectionUtils;
16 |  |
17 |  |
18 | 0 |
     public class BeanUtils {
19 |  |
20 |  |
       /**
21 |  |
        * <pre>
22 |  |
        *     List<UserBean> userBeans = userDao.queryUsers();
23 |  |
        *     List<UserDTO> userDTOs = BeanUtil.batchTransform(UserDTO.class, userBeans);
24 |  |
        * </pre>
25 |  |
        */
26 |  |
       public static <T> List<T> batchTransform(final Class<T> clazz, List<? extends Object> srcList) {
27 | 0 |
         if (CollectionUtils.isEmpty(srcList)) {
28 | 0 |
           return Collections.emptyList();
29 |  |
         }
30 |  |
31 | 0 |
         List<T> result = new ArrayList<>(srcList.size());
32 | 0 |
         for (Object srcObject : srcList) {
33 | 0 |
           result.add(transfrom(clazz, srcObject));
34 | 0 |
         }
35 | 0 |
         return result;
36 |  |
       }
37 |  |
38 |  |
       /**
39 |  |
        * 封装{@link org.springframework.beans.BeanUtils#copyProperties}，惯用与直接将转换结果返回
40 |  |
        *
41 |  |
        * <pre>
42 |  |
        *      UserBean userBean = new UserBean("username");
43 |  |
        *      return BeanUtil.transform(UserDTO.class, userBean);
44 |  |
        * </pre>
45 |  |
        */
46 |  |
       public static <T> T transfrom(Class<T> clazz, Object src) {
47 | 0 |
         if (src == null) {
48 | 0 |
           return null;
49 |  |
         }
50 | 0 |
         T instance = null;
51 |  |
         try {
52 | 0 |
           instance = clazz.newInstance();
53 | 0 |
         } catch (Exception e) {
54 | 0 |
           throw new RuntimeException(e);
55 | 0 |
         }
56 | 0 |
         org.springframework.beans.BeanUtils.copyProperties(src, instance, getNullPropertyNames(src));
57 | 0 |
         return instance;
58 |  |
       }
59 |  |
60 |  |
       private static String[] getNullPropertyNames(Object source) {
61 | 0 |
         final BeanWrapper src = new BeanWrapperImpl(source);
62 | 0 |
         PropertyDescriptor[] pds = src.getPropertyDescriptors();
63 |  |
64 | 0 |
         Set<String> emptyNames = new HashSet<String>();
65 | 0 |
         for (PropertyDescriptor pd : pds) {
66 | 0 |
           Object srcValue = src.getPropertyValue(pd.getName());
67 | 0 |
           if (srcValue == null) emptyNames.add(pd.getName());
68 |  |
         }
69 | 0 |
         String[] result = new String[emptyNames.size()];
70 | 0 |
         return emptyNames.toArray(result);
71 |  |
       }
72 |  |
73 |  |
       /**
74 |  |
        * 用于将一个列表转换为列表中的对象的某个属性映射到列表中的对象
75 |  |
        *
76 |  |
        * <pre>
77 |  |
        *      List<UserDTO> userList = userService.queryUsers();
78 |  |
        *      Map<Integer, userDTO> userIdToUser = BeanUtil.mapByKey("userId", userList);
79 |  |
        * </pre>
80 |  |
        *
81 |  |
        * @param key 属性名
82 |  |
        */
83 |  |
       @SuppressWarnings("unchecked")
84 |  |
       public static <K, V> Map<K, V> mapByKey(String key, List<? extends Object> list) {
85 | 0 |
         Map<K, V> map = new HashMap<K, V>();
86 | 0 |
         if (CollectionUtils.isEmpty(list)) {
87 | 0 |
           return map;
88 |  |
         }
89 |  |
         try {
90 | 0 |
           Class<? extends Object> clazz = list.get(0).getClass();
91 | 0 |
           Field field = deepFindField(clazz, key);
92 | 0 |
           if (field == null) throw new IllegalArgumentException("Could not find the key");
93 | 0 |
           field.setAccessible(true);
94 | 0 |
           for (Object o : list) {
95 | 0 |
             map.put((K) field.get(o), (V) o);
96 | 0 |
           }
97 | 0 |
         } catch (Exception e) {
98 | 0 |
           throw new RuntimeException();
99 | 0 |
         }
100 | 0 |
         return map;
101 |  |
       }
102 |  |
103 |  |
       /**
104 |  |
        * 根据列表里面的属性聚合
105 |  |
        *
106 |  |
        * <pre>
107 |  |
        *       List<ShopDTO> shopList = shopService.queryShops();
108 |  |
        *       Map<Integer, List<ShopDTO>> city2Shops = BeanUtil.aggByKeyToList("cityId", shopList);
109 |  |
        * </pre>
110 |  |
        */
111 |  |
       @SuppressWarnings("unchecked")
112 |  |
       public static <K, V> Map<K, List<V>> aggByKeyToList(String key, List<? extends Object> list) {
113 | 0 |
         Map<K, List<V>> map = new HashMap<K, List<V>>();
114 | 0 |
         if (CollectionUtils.isEmpty(list)) {// 防止外面传入空list
115 | 0 |
           return map;
116 |  |
         }
117 |  |
         try {
118 | 0 |
           Class<? extends Object> clazz = list.get(0).getClass();
119 | 0 |
           Field field = deepFindField(clazz, key);
120 | 0 |
           if (field == null) throw new IllegalArgumentException("Could not find the key");
121 | 0 |
           field.setAccessible(true);
122 | 0 |
           for (Object o : list) {
123 | 0 |
             K k = (K) field.get(o);
124 | 0 |
             if (map.get(k) == null) {
125 | 0 |
               map.put(k, new ArrayList<V>());
126 |  |
             }
127 | 0 |
             map.get(k).add((V) o);
128 | 0 |
           }
129 | 0 |
         } catch (Exception e) {
130 | 0 |
           throw new RuntimeException();
131 | 0 |
         }
132 | 0 |
         return map;
133 |  |
       }
134 |  |
135 |  |
       /**
136 |  |
        * 用于将一个对象的列表转换为列表中对象的属性集合
137 |  |
        *
138 |  |
        * <pre>
139 |  |
        *     List<UserDTO> userList = userService.queryUsers();
140 |  |
        *     Set<Integer> userIds = BeanUtil.toPropertySet("userId", userList);
141 |  |
        * </pre>
142 |  |
        */
143 |  |
       @SuppressWarnings("unchecked")
144 |  |
       public static <K> Set<K> toPropertySet(String key, List<? extends Object> list) {
145 | 0 |
         Set<K> set = new HashSet<K>();
146 | 0 |
         if (CollectionUtils.isEmpty(list)) {// 防止外面传入空list
147 | 0 |
           return set;
148 |  |
         }
149 |  |
         try {
150 | 0 |
           Class<? extends Object> clazz = list.get(0).getClass();
151 | 0 |
           Field field = deepFindField(clazz, key);
152 | 0 |
           if (field == null) throw new IllegalArgumentException("Could not find the key");
153 | 0 |
           field.setAccessible(true);
154 | 0 |
           for (Object o : list) {
155 | 0 |
             set.add((K)field.get(o));
156 | 0 |
           }
157 | 0 |
         } catch (Exception e) {
158 | 0 |
           throw new RuntimeException(e);
159 | 0 |
         }
160 | 0 |
         return set;
161 |  |
       }
162 |  |
163 |  |
164 |  |
       private static Field deepFindField(Class<? extends Object> clazz, String key) {
165 | 0 |
         Field field = null;
166 | 0 |
         while (!clazz.getName().equals(Object.class.getName())) {
167 |  |
           try {
168 | 0 |
             field = clazz.getDeclaredField(key);
169 | 0 |
             if (field != null) {
170 | 0 |
               break;
171 |  |
             }
172 | 0 |
           } catch (Exception e) {
173 | 0 |
             clazz = clazz.getSuperclass();
174 | 0 |
           }
175 |  |
         }
176 | 0 |
         return field;
177 |  |
       }
178 |  |
179 |  |
       /**
180 |  |
        * 获取某个对象的某个属性
181 |  |
        */
182 |  |
       public static Object getProperty(Object obj, String fieldName) {
183 |  |
         try {
184 | 0 |
           Field field = deepFindField(obj.getClass(), fieldName);
185 | 0 |
           if (field != null) {
186 | 0 |
             field.setAccessible(true);
187 | 0 |
             return field.get(obj);
188 |  |
           }
189 | 0 |
         } catch (Exception e) {
190 |  |
           // ig
191 | 0 |
         }
192 | 0 |
         return null;
193 |  |
       }
194 |  |
195 |  |
       /**
196 |  |
        * 设置某个对象的某个属性
197 |  |
        */
198 |  |
       public static void setProperty(Object obj, String fieldName, Object value) {
199 |  |
         try {
200 | 0 |
           Field field = deepFindField(obj.getClass(), fieldName);
201 | 0 |
           if (field != null) {
202 | 0 |
             field.setAccessible(true);
203 | 0 |
             field.set(obj, value);
204 |  |
           }
205 | 0 |
         } catch (Exception e) {
206 |  |
           // ig
207 | 0 |
         }
208 | 0 |
       }
209 |  |
210 |  |
       /**
211 |  |
        *
212 |  |
        * @param source
213 |  |
        * @param target
214 |  |
        */
215 |  |
       public static void copyProperties(Object source, Object target, String... ignoreProperties) {
216 | 0 |
         org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
217 | 0 |
       }
218 |  |
219 |  |
       /**
220 |  |
        * The copy will ignore <em>BaseEntity</em> field
221 |  |
        *
222 |  |
        * @param source
223 |  |
        * @param target
224 |  |
        */
225 |  |
       public static void copyEntityProperties(Object source, Object target) {
226 | 0 |
         org.springframework.beans.BeanUtils.copyProperties(source, target, COPY_IGNORED_PROPERTIES);
227 | 0 |
       }
228 |  |
229 | 0 |
       private static final String[] COPY_IGNORED_PROPERTIES = {"id", "dataChangeCreatedBy",
230 |  |
           "dataChangeCreatedTime", "dataChangeLastModifiedBy", "dataChangeLastModifiedTime"};
231 |  |
     }