一、工具类
public class BeanPropUtil {
public static Object addProperties(Object object,Map<String, Object> addProperties) {
Map<String, Class> propertyMap = new HashMap();
addProperties.forEach((k, v) -> {
propertyMap.put(k, v.getClass());
});
Object target = generateBean(object.getClass(), propertyMap);
BeanMap beanMap = new BeanMap(target);
addProperties.forEach((k, v) -> {
beanMap.put(k, v);
});
BeanUtils.copyBeanProp(target, object);
return target;
}
private static Object generateBean(Class superclass, Map<String, Class> propertyMap) {
BeanGenerator generator = new BeanGenerator();
if (null != superclass) {
generator.setSuperclass(superclass);
}
BeanGenerator.addProperties(generator, propertyMap);
return generator.create();
}
}
二、测试
Address address = new Address();
address.setCountry("c1");
address.setCity("c1");
Map<String, Object> addProperties = new HashMap();
addProperties.put("codeName","测试");
Object object = BeanPropUtil.addProperties(address,addProperties);
System.out.println(JSON.toJSONString(object));
{"city":"c1","codeName":"测试","country":"c1"}