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

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值