java动态给实体类添加属性
需要的jar包有两个: cglib-3.1.jar 和 google-collections-1.0.jar
如果是maven项目,就不需要cglib-3.1.jar,直接用spring自带的 org.springframework.cglib即可。
1、创建一个实体:DynamicBean
public class DynamicBean {
private Object target;
private BeanMap beanMap;
public DynamicBean(Class superclass, Map<String, Class> propertyMap) {
this.target = generateBean(superclass, propertyMap);
this.beanMap = BeanMap.create(this.target);
}
public void setValue(String property, Object value) {
beanMap.put(property, value);
}
public Object getValue(String property) {
return beanMap.get(property);
}
public Object getTarget() {
return this.target;
}
/**
* 根据属性生成对象
*
*/
private 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();
}
}
2、创建映射类,用来生成动态bean
public class ReflectUtil {
private static Logger logger = LoggerFactory.getLogger(ReflectUtil.class);
public static Object getObject(Object dest, Map<String, Object> addProperties) {
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(dest);
Map<String, Class> propertyMap = Maps.newHashMap();
for (PropertyDescriptor d : descriptors) {
if (!"class".equalsIgnoreCase(d.getName())) {
propertyMap.put(d.getName(), d.getPropertyType());
}
}
addProperties.forEach((k, v) -> {
String sclass = v.getClass().toString();
if(sclass.equals("class java.util.Date")) {//对日期进行处理
propertyMap.put(k, Long.class);
}else {
propertyMap.put(k, v.getClass());
}
});
DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap);
propertyMap.forEach((k, v) -> {
try {
if (!addProperties.containsKey(k)) {
dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(dest, k));
}
} catch (Exception e) {
logger.error("动态添加字段出错", e);
}
});
addProperties.forEach((k, v) -> {
try {
String sclass = v.getClass().toString();
if(sclass.equals("class java.util.Date")) {//动态添加的字段为date类型需要进行处理
Date date = (Date) v;
dynamicBean.setValue(k, date.getTime());
}