代码示例
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class Compare {
public static <T> Map<String, String> compare(T obj1, T Obj2)
throws Exception {
Map<String, String> result = new HashMap<String, String>();
Field[] fs = obj1.getClass().getDeclaredFields();//获取所有属性
for (Field f : fs) {
f.setAccessible(true);//设置访问性,反射类的方法,设置为true就可以访问private修饰的东西,否则无法访问
Object v1 = f.get(obj1);
Object v2 = f.get(Obj2);
result.put(f.getName(), String.valueOf(equals(v1, v2)));
}
return result;
}
public static boolean equals(Object obj1, Object obj2) {
if (obj1 == obj2) {
return true;
}
if (obj1 == null || obj2 == null) {
return false;
}
return obj1.equals(obj2);
}
public static void main(String[] args) throws Exception {
User user1 = new User(1,"11","11");
User user2 = new User(2,"22","11");
Map<String, String> result = compare(user1,user2);
System.out.println(result);
}
}
User实体类
public class User {
private Integer id;
private String name;
private String age;
/**
* 省略Get和Set方法。。。。
*/
public User(Integer id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}
}