Java判断两个自定义对象的各个属性是否相等

/**
 * Description: 判断两个对象的各个属性是否相同
 * Param: isUpdate为true,表示对原有属性值进行覆盖更改,为false,则只增加原来没有的属性值,原来有的属性值不进行更改
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 */ 
 @SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> T getNewVo(T older, T newer, boolean isUpdate) {
		boolean flag = false;
		try {
			Field[] fields = older.getClass().getDeclaredFields();
			Field field;
			String fieldName;
			Class clz = older.getClass();
			String getMethodName;
			String setMethodName;
			Method getMethod;
			Method setMethod;
			Object oldValue;
			Object newValue;
			
			for(int i = 0; i < fields.length; i++) {
			    field = fields[i];
			    fieldName = field.getName();
			    getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
			    setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
			    getMethod = clz.getMethod(getMethodName, new Class[] {});
			    setMethod = clz.getMethod(setMethodName, new Class[] {field.getType()});
			    oldValue = getMethod.invoke(older, new Object[]{});
			    newValue = getMethod.invoke(newer, new Object[]{});
		    	    if(oldValue == null) {//原属性值为null
		    		if(newValue != null) {//新属性值不为null,不管更新标志是否为true
		    			setMethod.invoke(older, newValue);//把新属性值赋值给原属性
		    			flag = true;
		    		}
		    	    } else if (!Objects.equals(oldValue, newValue)) {//原属性值不为null
		    		if(newValue != null && isUpdate) {//新属性值不为null,并且更新标志为true
		    			setMethod.invoke(older, newValue);//用新属性值覆盖原属性值
		    			flag = true;
		    		}
		    	    }
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return flag ? older : null;
	}

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值