1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
/** * 两个相同属性的对象赋值
*
* @param sourceObj
* @param targetObj
*/
public static void entityPropertiesCopy(Object sourceObj, Object targetObj) {
if (sourceObj == null || targetObj == null )
return ;
Class targetClass = null ;
//用java反射机制就可以, 可以做成通用的方法, 只要属性名和类型一样
Field[] sourceFields = null ;
try {
targetClass = targetObj.getClass();
sourceFields = sourceObj.getClass().getDeclaredFields();
} catch (Exception e) {
e.printStackTrace();
}
String fieldName = "" ;
Class fieldType = null ;
for ( int i = 0 ; i < sourceFields.length; i++) {
try {
fieldName = sourceFields[i].getName();
fieldType = sourceFields[i].getType();
Field targetField = targetClass.getDeclaredField(fieldName);
if (targetField != null && targetField.getType().equals(fieldType)) {
Method sourceGetter = sourceObj.getClass().getMethod(getGetMethodName(fieldName));
Method targetSetter = targetObj.getClass().getMethod(getSetMethodName(fieldName), new Class<?>[]{fieldType});
Object fieldValue = sourceGetter.invoke(sourceObj);
if (fieldValue != null ) {
targetSetter.invoke(targetObj, new Object[]{fieldValue});
}
}
} catch (NoSuchFieldException e) {
} catch (Exception e) {
e.printStackTrace();
}
}
} public static String getGetMethodName(String fieldName) {
String result = fieldName.substring( 0 , 1 ).toUpperCase() + fieldName.substring( 1 );
return "get" + result;
} public static String getSetMethodName(String fieldName) {
String result = fieldName.substring( 0 , 1 ).toUpperCase() + fieldName.substring( 1 );
return "set" + result;
} |
本文转自wauoen51CTO博客,原文链接:http://blog.51cto.com/7183397/1915661 ,如需转载请自行联系原作者