Object对象转换成MAP

该段代码展示了如何在Java中使用Introspector将实体对象转换为Map。首先检查对象是否为空,然后获取对象的BeanInfo,遍历其PropertyDescriptors以获取属性名和值,并过滤掉"class"属性。通过反射调用getter方法获取属性值,并将其放入Map中。同时,代码还检查了对象字段上的自定义注解`CChar`,用于处理特定长度的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private Map<String, Object> beanToMap throws Exception {
		//使用Introspector将实体对象转换成map
		if (item == null)
			return null;
		GzWhiteListInfoItem gzWhiteListInfoItem = item.getLineObject();
		Map<String, Object> map = new HashMap<String, Object>();
		BeanInfo beanInfo = Introspector.getBeanInfo(gzWhiteListInfoItem.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor property : propertyDescriptors) {
			String key = property.getName();
			//过滤class属性
			if (key.compareToIgnoreCase("class") == 0) {
				continue;
			}
			Method getter = property.getReadMethod();
			Object value = getter != null ? getter.invoke(gzWhiteListInfoItem) : null;
			map.put(key, value);
			
			//取注解(CChar自己定义的注解@CChar(value=3))
			CChar annoChar = GzWhiteListInfoItem.class.getField(key).getAnnotation(CChar.class);
			//下面的是取注解的长度和传参字段长度的比较(做笔记用,大家可以忽略),好处是在一个for循环里面可以比较所有的字段长度,不用一个个比较
			//取注解的长度annoChar.value(); 解析的长度:map.get(key).toString().length()
			if(annoChar != null && annoChar.value() < map.get(key).toString().length()) {
				//做相应的逻辑处理。。。。。
			}
		}
		return map;
	}			


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值