java 两个相同类型的对象比较指定属性的值

						两个相同类型的对象比较不同内容

/**
* 比较两个类型一样的对象中的值变更
* @param pre 变化前的对象
* @param last 变化后的对象
* @param map 需要比较的属性 map.put(“id”,“主键”);
* @return
*/
public static String compare(Object pre, Object last, Map<String,Object> map){
StringBuilder result=new StringBuilder();
Class preClass = pre.getClass();
Class lastClass = last.getClass();
//判断两个
if(!preClass.equals(lastClass)){
throw new RuntimeException(“两个对象类型不一致”);
}
if(CollectionUtils.isEmpty(map)){
throw new RuntimeException(“需要比较的属性不能为空”);
}
Set keys = map.keySet();
for(String key : keys){
//获取方法名
String methodName = “get” + key.substring(0, 1).toUpperCase() + key.substring(1);
Method preMethod;
Method lastMethod;
Object preValue;
Object lastValue;
try {
preMethod= preClass.getMethod(methodName);
lastMethod = lastClass.getMethod(methodName);
preValue = preMethod.invoke(pre);
lastValue = lastMethod.invoke(last);
}catch (Exception e){
throw new RuntimeException(“获取不到该方法”,e);
}
if("".equals(preValue)){
preValue =null;
}
if("".equals(lastValue)){
lastValue =null;
}
//如果前后两个值都是空,那么无需比较
if(!ObjectUtils.allNotNull(preValue)&&!ObjectUtils.allNotNull(lastValue)){
continue;
}else if(!ObjectUtils.allNotNull(preValue)&&ObjectUtils.allNotNull(lastValue)){
//前值为空,后值不为空
result.append(map.get(key) +“由空变为”+lastValue+";");
}else if(ObjectUtils.allNotNull(preValue)&&!ObjectUtils.allNotNull(lastValue)){
//前值不为空,后值为空
result.append(map.get(key)+“由”+preValue+“变为空;”);
}else if(ObjectUtils.allNotNull(preValue)&&ObjectUtils.allNotNull(lastValue)){
//两个都不为空
if (preValue.equals(lastValue)){
continue;
}
result.append(map.get(key)+“由”+preValue+“变为”+lastValue+";");
}
}
return result.toString();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值