日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

比較兩個對象屬性值是否相同方法

作者:夜,念如塵 更新時間: 2022-07-22 編程語言
    /**
     * 比較兩個對象屬性值是否相同
     *
     * @param obj1         比較對象1
     * @param obj2         比較對象2
     * @param cls          對象class
     * @param ignoreFields 忽略字段
     * @return true 相等
     */
    public static boolean compareTwoObject(Object obj1, Object obj2, Class cls, String[] ignoreFields) {
        boolean isEqual = true;
        BiPredicate biPredicate = new BiPredicate() {
            @Override
            public boolean test(Object object1, Object object2) {
                Object obj1 = object1 == null ? "" : object1;
                Object obj2 = object2 == null ? "" : object2;
                //BigDecimal 類型比較數(shù)值使用字符串不太合適,其它特殊類型可以繼續(xù)添加
                if (obj1 instanceof BigDecimal && obj2 instanceof BigDecimal) {
                    return ((BigDecimal) object1).compareTo((BigDecimal) object2) == 0;
                }
                if (obj1.equals(obj2)) {
                    return true;
                }
                return false;
            }
        };
        try {
            List<String> ignoreFieldList = Arrays.asList(ignoreFields);
            Field[] fields = cls.getDeclaredFields();
            for (Field field : fields) {
                if (ignoreFieldList.contains(field.getName())) {
                    continue;
                }
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), cls);
                Method getMethod = pd.getReadMethod();
                Object o1 = getMethod.invoke(obj1);
                Object o2 = getMethod.invoke(obj2);
                isEqual = biPredicate.test(o1, o2);
                if (!isEqual) {
                    break;
                }
            }
        } catch (Exception e) {
            isEqual = false;
        }
        return isEqual;
    }

原文鏈接:https://blog.csdn.net/xydxiong/article/details/120729884

欄目分類
最近更新