动态生成bean实体
程序员文章站
2022-05-24 09:10:53
...
最近工作中需要和前端同事配合,将传来的数据动态组装成dto实体,故可以用cglib动态代理来实现。
public class BeanDto {
public Object object = null;
public BeanMap beanMap = null;
public BeanDto() {
super();
}
public BeanDto(Map propertyMap) {
this.object = createDtoBean(propertyMap);
this.beanMap = BeanMap.create(this.object);
}
/**
* set方法
* @param property 属性名
* @param value 值
*/
public void setValue(String property, Object value) {
beanMap.put(property, value);
}
/**
* get方法
* @param property 属性名
* @return 值
*/
public Object getValue(String property) {
return beanMap.get(property);
}
/**
*获取Dto
* @return
*/
public Object getObject() {
return this.object;
}
private Object createDtoBean(Map propertyMap) {
BeanGenerator generator = new BeanGenerator();
Set keySet = propertyMap.keySet();
for (Iterator i = keySet.iterator(); i.hasNext();) {
String key = (String) i.next();
generator.addProperty(key, (Class) propertyMap.get(key));
}
return generator.create();
}
}
测试
public static void main(String[] args) throws ClassNotFoundException {
// 设置类成员属性
HashMap propertyMap = new HashMap();
propertyMap.put("id", Class.forName("java.lang.Integer"));
propertyMap.put("name", Class.forName("java.lang.String"));
propertyMap.put("address", Class.forName("java.lang.String"));
// 生成动态 Bean
FatherBeanDto bean = new FatherBeanDto(propertyMap);
// 给 Bean 设置值
bean.setValue("id", new Integer(123));
bean.setValue("name", "454");
bean.setValue("address", "789");
// 从 Bean 中获取值,当然了获得值的类型是 Object
System.out.println(" >> id = " + bean.getValue("id"));
System.out.println(" >> name = " + bean.getValue("name"));
System.out.println(" >> address = " + bean.getValue("address"));
// 获得bean的实体
Object object = bean.getObject();
// 通过反射查看所有方法名
Class clazz = object.getClass();
Method[] methods = clazz.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i].getName());
}
}
}