日期:2014-05-20 浏览次数:20850 次
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
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 DynaBeanCglibTest {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println("Generate JavaBean ...");
// 设置类成员属性
Map properties = new HashMap();
properties.put("id", Class.forName("java.lang.Integer"));
properties.put("name", Class.forName("java.lang.String"));
properties.put("address", Class.forName("java.lang.String"));
// 生成动态 Bean
CglibDynaBean bean = new CglibDynaBean(properties);
System.out.println(" OK!");
System.out.println("Set values ...");
// 给 Bean 设置值
bean.setValue("id", new Integer(123));
bean.setValue("name", "454");
bean.setValue("address", "789");
System.out.println(" OK!");
System.out.println("Get values");
// 从 Bean 中获取值,当然了获得值的类型是 Object
System.out.println(" >> id = " + bean.getValue("id"));
System.out.println(" >> name = " + bean.getValue("name"));
System.out.println(" >> address = " + bean.getValue("address"));
System.out.println("Class name");
// 查看动态 Bean 的类名
Class clazz = bean.getObject().getClass();
System.out.println(" >> " + clazz.getName());
System.out.println("Show all methods");
// 查看动态 Bean 中声明的方法
Method[] methods = clazz.getDeclaredMethods();
for(int i = 0; i < methods.length; i++) {
System.out.println(" >> " + methods[i].getName());
}
System.out.println("Show all properties");
// 查看动态 Bean 中声明的字段
Field[] fields = clazz.getDeclaredFields();
for(int i = 0; i < fields.length; i++) {
System.out.println(" >> " + fields[i].getName());
}
}
}
class CglibDynaBean {
private Object object = null;
private BeanMap beanMap = null;
public CglibDynaBean(Map properties) {
this.object = generateBean(properties);
this.beanMap = getBeanMap();
}
public void setValue(String property, Object value) {
beanMap.put(property, value);
}