怎么把两个对象不同属性值找出来
public class Student implements Serializable {
private String name;
private int age;
private String sex;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Student(String name, int age, String sex, String address) {
this.name = name;
this.age = age;
this.sex = sex;
this.address = address;
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Student stu1 = new Student("张三", 20, "男", "家");
Student stu2 = new Student("张三三", 20, "男", "家1");
}
}
//返回一个map以不同的属性名为key,value为一个list分别存obj1,obj2此属性名的值
public static Map<String,List<Object>> equals(Object obj1,Object obj2){
Map<String,List<Object>> map=new HashMap<String,List<Object>>();
if(obj1.getClass()==obj2.getClass()){//只有两个对象都是同一类型的才有可比性
Class clazz=obj1.getClass();
//获取object的属性描述
PropertyDescriptor[] pds=Introspector.getBeanInfo(clazz,Object.class).getPropertyDescriptors();
for(PropertyDescriptor pd:pds){//这里就是所有的属性了
String name=pd.getName();//属性名
Method readMethod=pd.getReadMethod();//get方法
//在obj1上调用get方法等同于获得obj1的属性值
Object o1=readMethod.invoke(obj1);
//在obj2上调用get方法等同于获得obj2的属性值
Object o2=readMethod.invoke(obj2);
if(!o1.equals(o2)){//比较这两个值是否相等,不等就可以放入map了
List<Object> list=new ArrayList<Object>();
list.add(o1);
list.add(02);
map.put(name,list);
}
}
}
return map;
}