比较两个对象,并返回值不相同的属性和值(判断对象哪个属性被修改,以及修改前和后的值)

写在前面
总共两部分:两个实体类,一个工具类

实体类(两个):

import lombok.Data;

import java.io.Serializable;

/**
 * @Description: 用于比较对象修改后的属性信息
 * @Date:   2021-04-21
 */
@Data
public class ModifiedPropertyInfo implements Serializable {
    // 对应的属性名
    private String propertyName;

    // 未修改之前的值
    private Object oldValue;

    // 修改后的值
    private Object newValue;
}
import lombok.Data;

/**
 * @Description: 用于比较对象,保存比较后的返回值信息
 * @Date:   2021-04-21
 */
@Data
public class PropertyModelInfo {
    //属性名
    private String propertyName;
    // 属性值
    private Object value;
    // 返回值类型
    private Class<?> returnType;
}

工具类(核心):

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @Description: 比较对象,并返回值不同的属性
 * @Date:   2021-04-21
 */
public class GlBgZdsxUtil {
    /**
     *  比较两个对象属性值是否相同
     *  如果不同返回修改过的属性信息
     * @param oldObj
     * @param newObj
     * @param ignoreProperties
     * @param <T>
     * @return 修改过的属性字段
     */
    public static <T> List<ModifiedPropertyInfo> getDifferentProperty(T oldObj , T newObj , String... ignoreProperties){
        if (oldObj != null && newObj != null) {
            // 比较全部字段
            if (ignoreProperties == null || ignoreProperties.length > 0) {
                if (oldObj.equals(newObj)) {
                    return Collections.emptyList();
                }
            }
            List<PropertyModelInfo> oldObjectPropertyValue = getObjectPropertyValue(oldObj, ignoreProperties);
            if (!CollectionUtils.isEmpty(oldObjectPropertyValue)) {
                List<ModifiedPropertyInfo> modifiedPropertyInfos = new ArrayList<>(oldObjectPropertyValue.size());

                List<PropertyModelInfo> newObjectPropertyValue = getObjectPropertyValue(newObj, ignoreProperties);
                Map<String , Object> objectMap = new HashMap<>(newObjectPropertyValue.size());
                // 获取新对象所有属性值
                for (PropertyModelInfo propertyModelInfo : newObjectPropertyValue) {
                    String propertyName = propertyModelInfo.getPropertyName();
                    Object value = propertyModelInfo.getValue();
                    objectMap.put(propertyName , value);
                }

                for (PropertyModelInfo propertyModelInfo : oldObjectPropertyValue) {
                    String propertyName = propertyModelInfo.getPropertyName();
                    Object value = propertyModelInfo.getValue();
                    if (objectMap.containsKey(propertyName)) {
                        Object newValue = objectMap.get(propertyName);
                        ModifiedPropertyInfo modifiedPropertyInfo = new ModifiedPropertyInfo();
                        if (value != null && newValue != null) {
                            if (!value.equals(newValue)) {
                                modifiedPropertyInfo.setPropertyName(propertyName);
                                modifiedPropertyInfo.setOldValue(value);
                                modifiedPropertyInfo.setNewValue(newValue);
                                modifiedPropertyInfos.add(modifiedPropertyInfo);
                            }
                        }else if (value != null && newValue == null || value== null && newValue != null){
                            modifiedPropertyInfo.setPropertyName(propertyName);
                            modifiedPropertyInfo.setOldValue(value);
                            modifiedPropertyInfo.setNewValue(newValue);
                            modifiedPropertyInfos.add(modifiedPropertyInfo);
                        }
                    }
                }
                return modifiedPropertyInfos;
            }
        }
        return Collections.emptyList();
    }


    /**
     *  通过反射获取对象的属性名称、getter返回值类型、属性值等信息
     * @param obj
     * @param ignoreProperties
     * @param <T>
     * @return
     */
    public static  <T> List<PropertyModelInfo> getObjectPropertyValue(T obj , String... ignoreProperties){
        if (obj != null) {
            Class<?> objClass = obj.getClass();
            PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(objClass);
            List<PropertyModelInfo> modelInfos = new ArrayList<>(propertyDescriptors.length);

            List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                Method readMethod = propertyDescriptor.getReadMethod();
                String name = propertyDescriptor.getName();
                if (readMethod != null && (ignoreList == null || !ignoreList.contains(name))) {
                    Object invoke = null;
                    Class<?> returnType = readMethod.getReturnType();
                    try {
                        invoke = readMethod.invoke(obj);
                        PropertyModelInfo propertyModelInfo = new PropertyModelInfo();
                        propertyModelInfo.setPropertyName(name);
                        propertyModelInfo.setValue(invoke);
                        propertyModelInfo.setReturnType(returnType);
                        modelInfos.add(propertyModelInfo);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        System.out.println("反射获取类【"+objClass.getName()+"】方法异常,");
                    }
                }
            }
            return modelInfos;
        }
        return Collections.emptyList();
    }
}

测试:

    public static void main(String[] args){

        //实体一
        GlWlzy glWlzy1 = new GlWlzy();
        glWlzy1.setId("12");
        glWlzy1.setYxbz("Y");
        glWlzy1.setXgrdm("sdfsdf");

        //实体二
        GlWlzy glWlzy2 = new GlWlzy();
        glWlzy2.setId("12");
        glWlzy2.setYxbz("Y");
        glWlzy2.setXgrdm("sdfsdf");

        //比较
        List<ModifiedPropertyInfo> modifiedPropertyInfos = getDifferentProperty(glWlzy1, glWlzy2);
        System.out.println(modifiedPropertyInfos);

        // 改变值
        glWlzy2.setYxbz("N");
        glWlzy2.setXgrdm("869696");
        modifiedPropertyInfos = getDifferentProperty(glWlzy1, glWlzy2);
        System.out.println(modifiedPropertyInfos);
        
        //  System.out.println("输出改变后的值:");
		//          for(int i = 0; i < modifiedPropertyInfos.size(); i++){
		//        System.out.println(modifiedPropertyInfos.get(i).getNewValue());
		//        }
    }
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
A:Java可以通过实现Comparable接口或者使用Comparator来对比两个类的对象属性。 1. 实现Comparable接口 假设我们有一个Person类,它有两个属性:姓名和年龄。我们可以在Person类中实现Comparable接口,覆写compareTo方法,对Person对象进行比较。 ``` public class Person implements Comparable<Person>{ private String name; private int age; public Person(String name, int age){ this.name = name; this.age = age; } public int compareTo(Person p) { return Integer.compare(this.age, p.getAge()); } //Getter and Setter } ``` 在compareTo方法中,我们可以通过比较年龄属性的大小来判断两个Person对象的大小。如果返回正数,则表示当对象大于参数对象;如果返回负数,则表示当对象小于参数对象;如果返回0,则表示当对象等于参数对象。 2. 使用Comparator 如果我们无法修改类的源代码,或者需要定制多种不同比较规则,则可以使用Comparator接口。 假设我们仍然有一个Person类,我们可以新建一个PersonAgeComparator类来实现Comparator接口,覆写compare方法: ``` public class PersonAgeComparator implements Comparator<Person>{ public int compare(Person p1, Person p2) { return Integer.compare(p1.getAge(), p2.getAge()); } } ``` 在compare方法中,我们同样比较两个Person对象的年龄属性,然后根据大小关系返回相应的。 使用时,我们可以通过调用Collections.sort方法,将Person对象的List进行排序: ``` List<Person> persons = new ArrayList<>(); persons.add(new Person("Tom", 25)); persons.add(new Person("Lucy", 18)); Collections.sort(persons, new PersonAgeComparator()); ``` 上述代码将Person对象的List按照年龄升序排序。如果需要降序排序,只需将比较方法中返回值的正负号反转即可。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阳光彩虹小红码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值