需求:在后台返回前台时,可能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;
}