public class ClassUtil {
/**
* 生成src类的子类,然后以newParName为字段把add写入新的子类
*/
public static Object covert(String newParName,Object src, Object add){
try {
HashMap<String,Class<?>> addMap = new HashMap<>();
HashMap<String, Object> addValMap = new HashMap<>();
addMap.put(newParName, Class.forName("java.lang.Object"));
addValMap.put(newParName, add);
return dynamicClass(src,addMap,addValMap,src.getClass());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param object 旧的对象
* @param addMap 动态需要添加的属性和属性类型
* @param addValMap 动态需要添加的属性和属性值
* @return 新的对象
*/
public static Object dynamicClass(Object object,HashMap<String,Class<?>> addMap,
HashMap<String, Object> addValMap,Class<?> supperClass) throws Exception {
HashMap<String, Object> returnMap = new HashMap<>();
HashMap<String,Class<?>> typeMap = new HashMap<>();
Class<?> type = object.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : propertyDescriptors) {
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(object);
//可以判断为 NULL不赋值
returnMap.put(propertyName, result);
typeMap.put(propertyName, descriptor.getPropertyType());
}
}
returnMap.putAll(addValMap);
typeMap.putAll(addMap);
//map转换成实体对象
DynamicBean bean = new DynamicBean(typeMap, supperClass);
//赋值
Set<String> keys = typeMap.keySet();
for (String key : keys) {
bean.setValue(key, returnMap.get(key));
}
return bean.getObject();
}
}
public class DynamicBean {
private Object object ; //动态生成的类
private BeanMap beanMap ; //存放属性名称以及属性的类型
public DynamicBean(HashMap<String,Class<?>> propertyMap , Class<?> supperClass) {
this.object = generateBean(propertyMap, supperClass);
this.beanMap = BeanMap.create(this.object);
}
private Object generateBean(HashMap<String,Class<?>> propertyMap,Class<?> supperClass) {
BeanGenerator generator = new BeanGenerator();
Set<String> keySet = propertyMap.keySet();
for (String key : keySet) {
generator.addProperty(key, propertyMap.get(key));
}
generator.setSuperclass(supperClass);
return generator.create();
}
public void setValue(Object property, Object value) {
beanMap.put(property, value);
}
public Object getValue(String property) {
return beanMap.get(property);
}
/**
* 得到该实体bean对象
*/
public Object getObject() {
return this.object;
}
}