java 判断两个bean 是否相等(技术点:反射)

原创
04/29 14:19
阅读数 397

知识点:

1. class.getDeclaredFields(); 获取类的所有字段

2.class.getMethods(); 获取类的方法

3.objValue = method.invoke(obj, new Object[] {}); 通过反射获取属性的值,obj对象,new Object[] {} 方法参数

 

1.bean

package com.qimh.springbootfiledemo.utils;

import com.alibaba.fastjson.JSONObject;

/**
 * @author ex-qiminhui001
 */
public class Person {
    private String name;
    private Integer age;
    private String[] friends;
    private JSONObject carts;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String[] getFriends() {
        return friends;
    }

    public void setFriends(String[] friends) {
        this.friends = friends;
    }

    public JSONObject getCarts() {
        return carts;
    }

    public void setCarts(JSONObject carts) {
        this.carts = carts;
    }
}

2.bean的比较工具类

package com.qimh.springbootfiledemo.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ex-qiminhui001
 * 判断两个bean是否相等
 */
public class BeanEquals {
    /**
     * 日志操作类
     */
    private static Logger logger = LoggerFactory.getLogger(BeanEquals.class);


    /**
     * 比较两个BEAN或MAP对象的值是否相等
     * 如果是BEAN与MAP对象比较时MAP中的key值应与BEAN的属性值名称相同且字段数目要一致
     * @param source
     * @param target
     * @return
     */
    public static boolean domainEquals(Object source, Object target) {
        if (source == null || target == null) {
            return false;
        }
        boolean rv = true;
        if (source instanceof Map) {
            rv = mapOfSrc(source, target, rv);
        } else {
            rv = classOfSrc(source, target, rv);
        }
        logger.info("THE EQUALS RESULT IS " + rv);
        return rv;
    }

    /**
     * 源目标为MAP类型时
     * @param source
     * @param target
     * @param rv
     * @return
     */
    private static boolean mapOfSrc(Object source, Object target, boolean rv) {
        HashMap<String, String> map = new HashMap<String, String>();
        map = (HashMap) source;
        for (String key : map.keySet()) {
            if (target instanceof Map) {
                HashMap<String, String> tarMap = new HashMap<String, String>();
                tarMap = (HashMap) target;
                if(tarMap.get(key)==null){
                    rv = false;
                    break;
                }
                if (!map.get(key).equals(tarMap.get(key))) {
                    rv = false;
                    break;
                }
            } else {
                String tarValue = getClassValue(target, key) == null ? "" : getClassValue(target, key).toString();
                if (!tarValue.equals(map.get(key))) {
                    rv = false;
                    break;
                }
            }
        }
        return rv;
    }

    /**
     * 源目标为非MAP类型时
     * @param source
     * @param target
     * @param rv
     * @return
     */
    private static boolean classOfSrc(Object source, Object target, boolean rv) {
        Class<?> srcClass = source.getClass();
        Field[] fields = srcClass.getDeclaredFields();
        for (Field field : fields) {
            String nameKey = field.getName();
            if (target instanceof Map) {
                HashMap<String, String> tarMap = new HashMap<String, String>();
                tarMap = (HashMap) target;
                String srcValue = getClassValue(source, nameKey) == null ? "" : getClassValue(source, nameKey)
                        .toString();
                if(tarMap.get(nameKey)==null){
                    rv = false;
                    break;
                }
                if (!tarMap.get(nameKey).equals(srcValue)) {
                    rv = false;
                    break;
                }
            } else {
                if (nameKey.equals("carts")){
                    System.out.println("field:" + nameKey);
                }
                if (nameKey.equals("friends")){
                    System.out.println("field:" + nameKey);
                }

                //数组类型
                if (!StringUtils.isEmpty(getClassValue(source, nameKey))  && getClassValue(source, nameKey) instanceof Object[]){
                    rv = Arrays.equals((Object[])getClassValue(source, nameKey),(Object[])getClassValue(target, nameKey));
                    break;
                }
                String srcValue = getClassValue(source, nameKey) == null ? "" : getClassValue(source, nameKey)
                        .toString();
                String tarValue = getClassValue(target, nameKey) == null ? "" : getClassValue(target, nameKey)
                        .toString();
                if (!srcValue.equals(tarValue)) {
                    rv = false;
                    break;
                }
            }
        }
        return rv;
    }

    /**
     * 根据字段名称取值
     * @param obj
     * @param fieldName
     * @return
     */
    public static Object getClassValue(Object obj, String fieldName) {
        if (obj == null) {
            return null;
        }
        try {
            Class beanClass = obj.getClass();
            Method[] ms = beanClass.getMethods();
            for (int i = 0; i < ms.length; i++) {
                // 非get方法不取
                if (!ms[i].getName().startsWith("get")) {
                    continue;
                }
                Object objValue = null;
                try {
                    objValue = ms[i].invoke(obj, new Object[] {});
                } catch (Exception e) {
                    logger.info("反射取值出错:" + e.toString());
                    continue;
                }
                if (objValue == null) {
                    continue;
                }
                if (ms[i].getName().toUpperCase().equals(fieldName.toUpperCase())
                        || ms[i].getName().substring(3).toUpperCase().equals(fieldName.toUpperCase())) {
                    return objValue;
                } else if (fieldName.toUpperCase().equals("SID")
                        && (ms[i].getName().toUpperCase().equals("ID") || ms[i].getName().substring(3).toUpperCase()
                        .equals("ID"))) {
                    return objValue;
                }
            }
        } catch (Exception e) {
            // logger.info("取方法出错!" + e.toString());
        }
        return null;
    }

    public static void main(String args[]) {
        Person person1 = new Person();
        person1.setName("张三");
        person1.setAge(20);
        JSONObject carts = new JSONObject();
        carts.put("bmw","宝马");
        carts.put("audi","奥迪");
        person1.setCarts(carts);
        person1.setFriends(new String[]{"tom","jim"});

        Person person2 = new Person();
        person2.setName("张三");
        person2.setAge(20);
        JSONObject carts2 = new JSONObject();
        carts2.put("bmw","宝马");
        carts2.put("audi","奥迪");
        person2.setCarts(carts2);
        person2.setFriends(new String[]{"tom","jim2"});

        System.out.println(domainEquals(person1,person2));

    }

}

3.比较结果:

field:friends
13:55:52.746 [main] INFO com.qimh.springbootfiledemo.utils.BeanEquals - THE EQUALS RESULT IS false
false

因为:person2.setFriends(new String[]{"tom","jim2"}); 与person1 的friends值不同

 

 

参考连接:https://www.cnblogs.com/chenyaqiang/p/5217497.html

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部