BeanUtils 踩坑指北

开发中有一步要发送 http 请求,参数为 map ,原本是有一个 bean 的, 于是就需要转换一下,

spring springframework 里有 BeanUtils,包含一个广为人知的 copyProperties 方法,于是点开这个类看了并没有转为map的,

虽然写一个转换方法也不算困难,不过由于时间关系,如果有现成的就直接导包用嘛,

然后搜索了一下,发现 org.apache.commons.beanutils.BeanUtils 有一个 populate(bean, map),的方法,就拿过来用了,

后来测试时候发现map是空的,就很懵逼,然后看了一下方法描述

@param properties Map keyed by property name, with the corresponding (String or String[]) value(s) to be set

就是说先要把 bean 的属性设为 map 的 key 才行,有 key 才会有值,而 new 的 map 当然是空的,结果还是空的。(⊙﹏⊙) 想不通开发者这么做的用意。

无奈正打算重写之际,发现它的第一个方法(因为是d开头)describe 参数为 bean ,return map,跑了一下测试打印出来是这样子的

{ CSNF=null, CDBH=ererger, class=class com.dto.PeopleData}

多一个 class 属性,然后 map.remove("class") ,就得到了想要的结果

{ CSNF=null, CDBH=ererger}

下面是得空补上的手动实现方法


             PeopleData people = new PeopleData();
		Map<String, String> params = new HashMap<String, String>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(people.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();

				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method m = property.getReadMethod();
					String value = (String) m.invoke(people);

					params.put(key, value);
				}

			}

		} catch (Exception e) {
			// TODO: handle exception
		}

原文地址:https://www.cnblogs.com/zfeixiang/p/9241811.html