/**
* 两个相同属性的对象赋值
*
* @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;
}
转载于:https://blog.51cto.com/7183397/1915661