利用反射:对比两个对象的所有属性值是否相同

package com.yonyou.cpu.purorder.launcher;
 
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
 
import org.springframework.util.StringUtils;
 
public class TestDate {
	/**
	 * Description: 获取修改内容
	 */
	public static String packageModifyContent(Object source, Object target) {
		StringBuffer modifyContent = new StringBuffer();
		if(null == source || null == target) {
			return "";
		}
		//取出source类
		Class sourceClass = source.getClass();
		
		Field[] sourceFields = sourceClass.getDeclaredFields();
		for(Field srcField : sourceFields) {
			String srcName = srcField.getName();			
			//获取srcField值
			String srcValue = getFieldValue(source, srcName) == null ? "" : getFieldValue(source, srcName).toString();
			//获取对应的targetField值
			String targetValue = getFieldValue(target, srcName) == null ? "" : getFieldValue(target, srcName).toString();
			if(StringUtils.isEmpty(srcValue) && StringUtils.isEmpty(targetValue)) {
				continue;
			}
			if(!srcValue.equals(targetValue)) {
				modifyContent.append(srcName + "由‘" + targetValue + "’修改为‘" + srcValue + "’;");
			}
			
		}
		return modifyContent.toString();
	}
	/**
	 * Description: 获取Obj对象的fieldName属性的值
	 */
	private static Object getFieldValue(Object obj, String fieldName) {
		Object fieldValue = null;
		if(null == obj) {
			return null;
		}
		Method[] methods = obj.getClass().getDeclaredMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			if(!methodName.startsWith("get")) {
				continue;
			}
			if(methodName.startsWith("get") && methodName.substring(3).toUpperCase().equals(fieldName.toUpperCase())) {
                 try {
                	 fieldValue = method.invoke(obj, new Object[] {});
                 } catch (Exception e) {
                	System.out.println("取值出错,方法名 " + methodName);
                    continue;
                 }
			}
		}
		return fieldValue;
	}
}

转载自:https://blog.csdn.net/lixingtao0520/article/details/77149079

你可能感兴趣的:(利用反射:对比两个对象的所有属性值是否相同)