package com.whyc.util;
|
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.beanutils.PropertyUtilsBean;
|
|
import java.beans.PropertyDescriptor;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
/**
|
* @className:ReflectUtil
|
* @description:动态生成类的属性、并且赋值
|
* @date:2018年4月3日 下午2:33:10
|
*/
|
@Slf4j
|
public class ReflectUtil {
|
|
//static Logger logger = LogManager.getLogger(ReflectUtil.class);
|
|
@SuppressWarnings("rawtypes")
|
public static Object getTarget(Object dest, Map<String, Object> addProperties) {
|
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
|
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(dest);
|
Map<String, Class> propertyMap = new HashMap<>();
|
for (PropertyDescriptor d : descriptors) {
|
if (!"class".equalsIgnoreCase(d.getName())) {
|
propertyMap.put(d.getName(), d.getPropertyType());
|
}
|
}
|
// add extra properties
|
addProperties.forEach((k, v) -> propertyMap.put(k, v.getClass()));
|
// new dynamic bean
|
DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap);
|
// add old value
|
propertyMap.forEach((k, v) -> {
|
try {
|
// filter extra properties
|
if (!addProperties.containsKey(k)) {
|
dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(dest, k));
|
}
|
} catch (Exception e) {
|
log.error(e.getMessage(), e);
|
}
|
});
|
// add extra value
|
addProperties.forEach((k, v) -> {
|
try {
|
dynamicBean.setValue(k, v);
|
} catch (Exception e) {
|
log.error(e.getMessage(), e);
|
}
|
});
|
Object target = dynamicBean.getTarget();
|
return target;
|
}
|
|
/*public static void setProperty(Object obj, String propertyName, Object value)
|
throws NoSuchFieldException, SecurityException,
|
IllegalArgumentException, IllegalAccessException {
|
// 根绝对象获取字节码文件
|
Class c = obj.getClass();
|
// 获取该对象的propertyName成员变量
|
Field field = c.getDeclaredField(propertyName); //注意你是通过参数来获取,不许加双引号“”
|
// 取消访问检查
|
field.setAccessible(true);
|
// 给对象的成员变量赋值为指定的值--->value
|
field.set(obj, value);
|
}
|
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
|
BattDataDTO entity = new BattDataDTO();
|
ReflectUtil.setProperty(entity,"time","hehe");
|
Map<String, Object> addProperties = new HashMap<>();
|
addProperties.put("day31", "你好");
|
Object obj = getTarget(entity, addProperties);
|
String s = ActionUtil.getGson().toJson(obj);
|
System.out.println(s);
|
}*/
|
}
|