Java暴力反射copy对象

/**
	 * 创建一个新的类 并赋给属性名相同类型相同的属性值
	 * @param o1 目标对象
	 * @param o2Class 赋值对象
	 * @throws IllegalAccessException
	 */
	public static  <T> T createObject(Object o1, Class<T> o2Class) throws IllegalAccessException, InstantiationException {
		T o2 = o2Class.newInstance();
		Class<?> o1Class = o1.getClass();
		//o1属性
		Field[] o1Fields = o1Class.getDeclaredFields();
		//o2属性
		Field[] o2Fields = o2Class.getDeclaredFields();
		//如果没有属性则不处理
		if (o1Fields.length == 0 ||o2Fields.length == 0){
			return o2;
		}
		//根据名称转小写然后分组
		Map<String, List<Field>> nameMap = Arrays.stream(o1Fields).collect(Collectors.groupingBy(s -> s.getName().toLowerCase()));
		for (Field o2Field : o2Fields) {
			List<Field> fields = nameMap.get(o2Field.getName().toLowerCase());
			//不存在名称相同不处理
			if (CollUtil.isEmpty(fields)){
				continue;

			}
			//名称相同的属性o1
			Field o1field = fields.get(0);
			//类型不同
			if (!o1field.getGenericType().toString().equalsIgnoreCase(o2Field.getGenericType().toString())){
				String o1Types = o1field.getGenericType().toString();
				String o2Types = o2Field.getGenericType().toString();
				String o1Type = o1Types.substring(o1Types.lastIndexOf(".")+1);
				String o2Type = o2Types.substring(o2Types.lastIndexOf(".")+1);
				//特殊情况排除
				if (!(o1Type.equals("int")&&o2Type.equals("Integer") ||
						o1Type.equals("Integer")&&o2Type.equals("int")||
						o1Type.equals("char")&&o2Type.equals("Character") ||
						o1Type.equals("Character")&&o2Type.equals("char"))){
					continue;
				}
			}
			//打破私有访问限制
			o2Field.setAccessible(true);
			o1field.setAccessible(true);
			//赋值
			o2Field.set(o2,o1field.get(o1));
		}
		return o2;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值