利用反射,比较两个对象的属性值,以及动态的为属性赋值

 1:比较两个对象的属性值,返回不同的属性+值

    /**
     * 比较旧对象与新对象的所有属性值
     * @param oldObj
     * @param newObj
     * @return 返回 <k,V>-><属性,新值>
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static Map<String, String> contrastObj(Object oldObj, Object newObj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        Class<?> clazz = oldObj.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        HashMap<String, String> map = new HashMap<>();
        for (Field field : declaredFields) {
            System.out.println(field);
            System.out.println("field:"+field.getName());
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            Method getMethod = pd.getReadMethod();
            Object o1 = getMethod.invoke(oldObj);
            Object o2 = getMethod.invoke(newObj);
            String oldStr = o1 == null ? "" : o1.toString();//避免空指针异常
            String newStr = o2 == null ? "" : o2.toString();
            if (!oldStr.equals(newStr)){
                map.put(field.getName(),newStr); //《属性,新值》\
            }
        }
        return map;
    }

2:动态为对象属性赋值

/**
 * @msg:  通过反射来动态调用get 和 set 方法
 /
public class ReflectHelper {
    private Class cls;
    /**
     * 传过来的对象
     */
    private Object obj;
    private HashMap<String, Method> getMethods = null;
    private HashMap<String, Method> setMethods = null;
    public ReflectHelper(Object o) {
        obj = o;
        initMethods();
    }
    public void initMethods() {
        getMethods = new HashMap<>();
        setMethods = new HashMap<>();
        cls = obj.getClass();
        Method[] methods = cls.getMethods();
// 定义正则表达式,从方法中过滤出getter / setter 函数.
        String gs = "get(\\w+)";
        Pattern getM = Pattern.compile(gs);
        String ss = "set(\\w+)";
        Pattern setM = Pattern.compile(ss);
        // 把方法中的"set" 或者 "get" 去掉,$1匹配第一个
        String rapl = "$1";
        String param;
        for (int i = 0; i < methods.length; ++i) {
            Method m = methods[i];
            String methodName = m.getName();
            if (Pattern.matches(gs, methodName)) {
                param = getM.matcher(methodName).replaceAll(rapl).toLowerCase();
                getMethods.put(param, m);
            } else if (Pattern.matches(ss, methodName)) {
                param = setM.matcher(methodName).replaceAll(rapl).toLowerCase();
                setMethods.put(param, m);
            } else {
                //非get/set方法
            }
        }
    }
    public boolean setMethodValue(String property,Object object) {
        Method m = setMethods.get(property.toLowerCase());
        if (m != null) {
            try {
            // 调用目标类的setter函数
                m.invoke(obj, object);
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
        }
        return false;
    }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值