动态创建javabean对于我们进行开发,会有一定的帮助,一下是使用cglib动态创建javabean的一个例子:
先贴上code:
package com.dalong.CreateCode;
import java.util.Iterator; import java.util.Map; import java.util.Set;
import net.sf.cglib.beans.BeanGenerator; import net.sf.cglib.beans.BeanMap;
public class CodeCreate {
/** * 实体Object */
private Object object = null;
/** * 属性map */
private BeanMap beanMap = null;
public CodeCreate()
{
super();
}
@SuppressWarnings("unchecked")
public CodeCreate(Map propertyMap) {
this.object = generateBean(propertyMap);
this.beanMap = BeanMap.create(this.object);
}
/** * 给bean属性赋值 * @param property 属性名 * @param value 值 */
public void setValue(String property, Object value)
{
beanMap.put(property, value);
}
/** * 通过属性名得到属性值 * @param property 属性名 * @return 值 */
public Object getValue(String property)
{
return beanMap.get(property);
}
/** * 得到该实体bean对象 * @return */
public Object getObject()
{
return this.object;
}
/** * @param propertyMap * @return */
@SuppressWarnings("unchecked")
private Object generateBean(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));
}
// generator.addProperties(generator, propertyMap); // 简写的方式
return generator.create();
}
}
一下是测试的代码:
package com.dalong.Test;
import java.lang.reflect.Method; import java.util.HashMap;
import com.dalong.CreateCode.CodeCreate;
public class TestClassMain {
public TestClassMain() { // TODO Auto-generated constructor stub }
/** * @param args * @throws ClassNotFoundException */
public static void main(String[] args) throws ClassNotFoundException
{
// TODO Auto-generated method stub
// 设置类成员属性
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
CodeCreate bean = new CodeCreate(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());
}
}
}
代码比较简单,在实际的使用过程中可以进行改进。