提取Bean中字段以Map返回

需求:在后台返回前台时,可能bean中仅有几个字段想要,因此就写上了类似的代码

        Map<String,Object> result  = new HashMap<>();
        result.put("id",musicInfo.getId());
        result.put("isOriginal",musicInfo.getIsOriginal());
        result.put("createPersonId",musicInfo.getCreatePersonId());
        result.put("musicName",musicInfo.getMusicName());
        return result;

但是这种方式设置一会儿就晕了,于是想到了 org.springframework.beans下的copyProperties方法,但是该方法提供提取bean,忽略哪些字段:

BeanUtils.copyProperties(musicInfo,musicInfoCopy,new String[]{"updateTime","createtime","status"});

但是返回的musicInfoCopy 被忽略的字段会为空,前端看起来还是乱乱的,因此复写一个方法,输入要保留的字段,先看下调用效果:

调用方式:

Map musicInfoMap = PubMethod.copyProperties(musicInfo, new String[]{"id", "musicType", "musicTypeId", "musicName"});

结果json:

            {        
                "id": 317694598307840,
                "musicName": "非常流行的音乐"
                "musicTypeId": 307899564679168,
                "musicType": "流行音乐"
            }

是不清凉了很多,将我封装的方法贴上

/**
	 *将给定源bean的属性值复制到新的map中。
	 *并且可以单独执行要包含的字段 如果制定字段为null  那就按照全部字段
	 * @param source the source bean
	 * @param includeProperties array of property names to include
	 * @throws BeansException if the copying failed
	 */
	public static Map<String,Object> copyProperties(Object source, String[] includeProperties)
			throws BeansException {
		//判断空
		Assert.notNull(source, "Source must not be null");
		//得到源类
		Class<?> sourceEditable = source.getClass();
		//得到源类搜索的字段
		PropertyDescriptor[] sourcePds = BeanUtils.getPropertyDescriptors(sourceEditable);
		//对包含字段数组转集合
		List<String> includeList = (includeProperties != null) ? Arrays.asList(includeProperties) : null;
		//初始化返回的Map
		Map<String,Object> resultMap = new HashMap<>(sourcePds.length);
		for (PropertyDescriptor sourcePd : sourcePds) {
			//得到源类中的方法   并判断是否有包含字段  如果有包含字段那么就按照包含字段去赋值
			if (sourcePd.getWriteMethod() != null &&
					(includeProperties == null || (includeList.contains(sourcePd.getName())))) {
				PropertyDescriptor sourcePdPd = getPropertyDescriptor(source.getClass(), sourcePd.getName());
				if (sourcePdPd != null && sourcePdPd.getReadMethod() != null) {
					try {
						Method readMethod = sourcePdPd.getReadMethod();
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						//将字段名 和参数写入到结果map中
						resultMap.put(sourcePd.getName(),value);
					}
					catch (Throwable ex) {
						throw new FatalBeanException("Could not copy properties from source to target", ex);
					}
				}
			}
		}
		return resultMap;
	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值