java动态给类添加属性
maven依赖
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
动态Bean类
package com.wl.putrecord;
import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;
import java.util.Map;
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();
}
}
工具类
package com.wl.putrecord;
import avro.shaded.com.google.common.collect.Maps;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.Map;
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());
}else {
dynamicBean.setValue(k, v);
}
} catch (Exception e) {
logger.error("动态添加字段值出错", e);
}
});
Object obj = dynamicBean.getTarget();
return obj;
}
}
测试类
package com.wl.putrecord;
import java.lang.reflect.Field;
/**
* @author 没有梦想的java菜鸟
* @Date 创建时间:2022/4/27 上午10:38
* @qq 2315290571
* @Description a
*/
public class Test {
public static void main(String[] args) throws Exception {
User user = new User();
user.setId(1004);
user.setUsername("小张");
HashMap<String, Object> propertiesMap = new HashMap<>();
propertiesMap.put("password","123456");
User object = (User) ReflectUtil.getObject(user, propertiesMap);
System.out.println(JSON.toJSONString(object));
}
}