比较两个对象的属性是否进行了修改
public static <T> Object compareFiled(T source, T target) {
Object object = new Object();
try {
Field[] fields = getAllFields(source);
for (int j = 0; j < fields.length; j++) {
fields[j].setAccessible(true);
if (StringUtils.isEmpty(fields[j].get(source))) {
setValues(fields[j].getName(), fields[j].get(source), object );
} else if (!fields[j].get(source).equals(fields[j].get(target))) {
setValues(fields[j].getName(), fields[j].get(source), object );
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return object;
}
public static Field[] getAllFields(Object object) {
Class clazz = object.getClass();
List<Field> fieldList = new ArrayList<>();
while (clazz != null) {
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
private static Object setValuesInfo(String name, Object value, Object object) {
switch (name) {
case "filed1":
object.setFiled1(value == null ? null : String.valueOf(value));
break;
case "filed2":
object.setFiled2(value == null ? null : String.valueOf(value));
break;
case "filed3":
object.setfFiled3(value == null ? null : String.valueOf(value));
break;
}
return object;
}
复制同名的field的值从{from} copy 到 {to}
public static void copy(Object from, Object to) {
Method[] Methods = from.getClass().getMethods();
try {
for (Method method : Methods) {
if (!method.getName().startsWith("get"))
continue;
String writeMethodName = "s"+ method.getName().substring(1);
Method writeMethod = null;
try {
writeMethod = to.getClass().getMethod(writeMethodName,
method.getReturnType());
} catch (Exception e) {
continue;
}
Object value = method.invoke(from);
writeMethod.invoke(to, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}