---
title: "利用反射比较同一个对象的两个实例的具体值的异同"
author: "falseking"
date: "2016-09-28T21:44:18Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2016-09-28T21:42:25Z"
id: 2327694
url: "https://falseking.iteye.com/blog/2327694"
---

/\**

 * 比较同一个类的两个对象示例的不一样的内容，并输出不一样的字段内容

 * &lt;br/&gt; 属性字段为基本数据类型

 * 

 * @author FALSE KING create

 * @date 2016年9月23日 下午4:36:38

 \*/

public class ModelComparator&lt;T&gt; {

 

/\**

\* 比较内容，输出不一样的字段内容&lt;br/&gt;

\* 属性字段为基本数据类型

* 

\* @param oldModel  修改前的对象

\* @param newModel 修改后的对象

\* @param exceptFileds 排除的属性字段列表

\* @return

\*/

public String compare(T oldModel,T newModel,List&lt;String&gt; exceptFileds) {

List&lt;String&gt; result = new ArrayList();

 

Field\[] oldFields = oldModel.getClass().getDeclaredFields();

for (Field f : oldFields) {

String name = f.getName();

if(CollectionUtils.isNotEmpty(exceptFileds) && exceptFileds.contains(name)){

continue;

}

String methodName = "get" + name.substring(0, 1).toUpperCase() + 

name.substring(1);

try {

Object oldVal = oldModel.getClass().getMethod(methodName).invoke(oldModel);

Object newVal = newModel.getClass().getMethod(methodName).invoke(newModel);

if(oldVal != null && !oldVal.equals(newVal)){

 

result.add(String.valueOf(oldVal) + "修改为" +String.valueOf(newVal)+ "\\n") ;

}

} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException

| NoSuchMethodException | SecurityException e) {

}

}

String str = "";

if(CollectionUtils.isNotEmpty(result)){

str = result.stream().reduce((sum,e)-&gt;sum += e).get();

}

return str;

}

}