利用Java反射实现JavaBean对象相同属性复制并初始化目标对象为空的属性的BeanUtils

有时遇到将数据传输对象转换成JSON串会将属性值为空的属性去掉,利用Java反射实现JavaBean对象数据传输对象的相同属性复制并初始化数据传输对象属性为空的属性,然后转换成JSON串

  1 package com.banksteel.util;
  2 
  3 
  4 import java.lang.reflect.Field;
  5 import java.lang.reflect.Method;
  6 import java.util.*;
  7 
  8 /**
  9  * @version 3.0.0
 10  * @description: copy对象属性工具类
 11  * @projectName:banksteel-util
 12  * @className:BeanUtil.java
 13  * @see: com.banksteel.util
 14  * @author 15  * @createTime:2017年2月7日 上午9:15:23
 16  */
 17 public class BeanUtils {
 18     private final static String GETTER = "get";
 19     private final static String SETTER = "set";
 20     private final static String IS = "is";
 21     private final static String INTEGER = "java.lang.Integer";
 22     private final static String DOUBLE = "java.lang.Double";
 23     private final static String LONG = "java.lang.Long";
 24     private final static String STRING = "java.lang.String";
 25     private final static String SET = "java.util.Set";
 26     private final static String LIST = "java.util.List";
 27     private final static String MAP = "java.util.Map";
 28 
 29     /**
 30      * 对象之间相同属性复制
 31      *
 32      * @param source 源对象
 33      * @param target 目标对象
 34      */
 35     public static void copyProperties(Object source, Object target) {
 36         try {
 37             copyExclude(source, target, null);
 38         } catch (Exception e) {
 39             e.printStackTrace();
 40         }
 41         try {
 42             initBeanProperties(target);
 43         } catch (Exception e) {
 44             e.printStackTrace();
 45         }
 46     }
 47 
 48     /**
 49      * @param source       源对象
 50      * @param target       目标对象
 51      * @param excludsArray 排除属性列表
 52      * @description: 对象之间相同属性复制
 53      * @author 54      * @createTime:2017年2月8日 下午5:07:11
 55      */
 56     public static void copyPropertiesExclude(Object source, Object target, String[] excludsArray) {
 57         try {
 58             copyExclude(source, target, excludsArray);
 59         } catch (Exception e) {
 60             e.printStackTrace();
 61         }
 62         try {
 63             initBeanProperties(target);
 64         } catch (Exception e) {
 65             e.printStackTrace();
 66         }
 67     }
 68 
 69     /**
 70      * @param source       源对象
 71      * @param target       目标对象
 72      * @param includsArray 包含的属性列表
 73      * @description: 对象之间相同属性复制
 74      * @author 75      * @createTime:2017年2月8日 下午5:07:11
 76      */
 77     public static void copyPropertiesInclude(Object source, Object target, String[] includsArray) {
 78         try {
 79             copyInclude(source, target, includsArray);
 80         } catch (Exception e) {
 81             e.printStackTrace();
 82         }
 83         try {
 84             initBeanProperties(target);
 85         } catch (Exception e) {
 86             e.printStackTrace();
 87         }
 88     }
 89 
 90     private static boolean isGetter(Method method) {
 91         String methodName = method.getName();
 92         Class<?> returnType = method.getReturnType();
 93         Class<?> parameterTypes[] = method.getParameterTypes();
 94         if (returnType.equals(void.class)) {
 95             return false;
 96         }
 97         if ((methodName.startsWith(GETTER) || methodName.startsWith(IS)) && parameterTypes.length == 0) {
 98             return true;
 99         }
100         return false;
101     }
102 
103     private static boolean isSetter(Method method) {
104         String methodName = method.getName();
105         Class<?> parameterTypes[] = method.getParameterTypes();
106 
107         if (methodName.startsWith(SETTER) && parameterTypes.length == 1) {
108             return true;
109         }
110         return false;
111     }
112 
113     /**
114      * 复制对象属性
115      *
116      * @param source
117      * @param target
118      * @param excludsArray 排除属性列表
119      * @throws Exception
120      */
121     private static void copyExclude(Object source, Object target, String[] excludsArray) throws Exception {
122         List<String> excludesList = null;
123 
124         if (excludsArray != null && excludsArray.length > 0) {
125             excludesList = Arrays.asList(excludsArray); // 构造列表对象
126         }
127         Method[] sourceMethods = source.getClass().getDeclaredMethods();
128         Method[] targetMethods = target.getClass().getDeclaredMethods();
129         Method sourceMethod = null, targetMethod = null;
130         String sourceMethodName = null, targetMethodName = null;
131 
132         for (int i = 0; i < sourceMethods.length; i++) {
133 
134             sourceMethod = sourceMethods[i];
135             sourceMethodName = sourceMethod.getName();
136 
137             if (!isGetter(sourceMethod)) {
138                 continue;
139             }
140             // 排除列表检测
141             if (excludesList != null && excludesList.contains(sourceMethodName.substring(3).toLowerCase())) {
142                 continue;
143             }
144             targetMethodName = SETTER + sourceMethodName.substring(3);
145             targetMethod = findMethodByName(targetMethods, targetMethodName);
146 
147             if (targetMethod == null) {
148                 continue;
149             }
150 
151             if (!isSetter(targetMethod)) {
152                 continue;
153             }
154 
155             Object value = sourceMethod.invoke(source, new Object[0]);
156 
157             if (value == null) {
158                 continue;
159             }
160             // 集合类判空处理
161             if (value instanceof Collection) {
162                 Collection<?> newValue = (Collection<?>) value;
163 
164                 if (newValue.size() <= 0) {
165                     continue;
166                 }
167             }
168 
169             targetMethod.invoke(target, new Object[]
170                     {value});
171         }
172     }
173 
174     private static void copyInclude(Object source, Object target, String[] includsArray) throws Exception {
175         List<String> includesList = null;
176 
177         if (includsArray != null && includsArray.length > 0) {
178             includesList = Arrays.asList(includsArray);
179         } else {
180             return;
181         }
182         Method[] sourceMethods = source.getClass().getDeclaredMethods();
183         Method[] targetMethods = target.getClass().getDeclaredMethods();
184         Method sourceMethod = null, targetMethod = null;
185         String sourceMethodName = null, targetMethodName = null;
186 
187         for (int i = 0; i < sourceMethods.length; i++) {
188             sourceMethod = sourceMethods[i];
189             sourceMethodName = sourceMethod.getName();
190 
191             if (!isGetter(sourceMethod)) {
192                 continue;
193             }
194 
195             // 排除列表检测
196             String str = sourceMethodName.substring(3);
197 
198             if (!includesList.contains(str.substring(0, 1).toLowerCase() + str.substring(1))) {
199                 continue;
200             }
201 
202             targetMethodName = SETTER + sourceMethodName.substring(3);
203             targetMethod = findMethodByName(targetMethods, targetMethodName);
204 
205             if (targetMethod == null) {
206                 continue;
207             }
208 
209             if (!isSetter(targetMethod)) {
210                 continue;
211             }
212 
213             Object value = sourceMethod.invoke(source, new Object[0]);
214 
215             if (value == null) {
216                 continue;
217             }
218 
219             // 集合类判空处理
220             if (value instanceof Collection) {
221                 Collection<?> newValue = (Collection<?>) value;
222 
223                 if (newValue.size() <= 0) {
224                     continue;
225                 }
226             }
227 
228             targetMethod.invoke(target, new Object[]
229                     {value});
230         }
231     }
232 
233     /**
234      * 从方法数组中获取指定名称的方法
235      *
236      * @param methods
237      * @param name
238      * @return
239      */
240     private static Method findMethodByName(Method[] methods, String name) {
241         for (int j = 0; j < methods.length; j++) {
242             if (methods[j].getName().equals(name)) {
243 
244                 return methods[j];
245             }
246         }
247         return null;
248     }
249 
250     private static boolean isTrimEmpty(String str) {
251 
252         return (str == null) || (str.trim().isEmpty());
253     }
254 
255     /**
256      * @param obj
257      * @throws Exception
258      * @description: 初始化对象为空的属性
259      * @author260      * @createTime:2017年2月7日 下午3:31:14
261      */
262     private static void initBeanProperties(Object obj) throws Exception {
263         Class<?> classType = obj.getClass();
264         for (Field field : classType.getDeclaredFields()) {
265             // 获取对象的get,set方法
266             String getMethodName = GETTER + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
267             String setMethodName = SETTER + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
268             // 调用对象的get方法获取属性值
269             Method getMethod = classType.getDeclaredMethod(getMethodName, new Class[]
270                     {});
271             Object value = getMethod.invoke(obj, new Object[]
272                     {});
273 
274             // String fieldType = field.getType().toString();
275             String fieldType = field.getType().toString();
276             if (value == null && !isTrimEmpty(fieldType)) {
277                 // 调用对象的set方法把属性值初始化
278                 if (fieldType.contains(INTEGER)) {
279                     Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
280                             {field.getType()});
281                     setMethod.invoke(obj, new Object[]
282                             {0});
283                 } else if (fieldType.contains(DOUBLE)) {
284                     Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
285                             {field.getType()});
286                     setMethod.invoke(obj, new Object[]
287                             {0.0});
288                 } else if (fieldType.contains(LONG)) {
289                     Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
290                             {field.getType()});
291                     setMethod.invoke(obj, new Object[]
292                             {0L});
293                 } else if (fieldType.contains(STRING)) {
294                     Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
295                             {field.getType()});
296                     setMethod.invoke(obj, new Object[]
297                             {""});
298                 } else if (fieldType.contains(SET)) {
299                     Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
300                             {field.getType()});
301                     setMethod.invoke(obj, new Object[]
302                             {new HashSet<Object>()});
303                 } else if (fieldType.contains(LIST)) {
304                     Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
305                             {field.getType()});
306                     setMethod.invoke(obj, new Object[]
307                             {new ArrayList<Object>()});
308                 } else if (fieldType.contains(MAP)) {
309                     Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]
310                             {field.getType()});
311                     setMethod.invoke(obj, new Object[]
312                             {new HashMap<Object, Object>()});
313                 }
314             }
315         }
316     }
317 
318 }

posted on 2017-02-10 23:31  Java&coder  阅读(978)  评论(0编辑  收藏  举报

导航