轉至:http://ckwang17.iteye.com/blog/963881
cglib
是一個開源專案!
是一個強大的,高效能,高質量的Code生成類庫,它可以在執行期擴充套件Java類與實現Java介面。許多開源專案都用到了它,如Hibernate,Spring之類用它來實現動態代理。
簡單樣例—動態生成bean
樣例說明:建立一個動態實體bean,使用cglib動態加入屬性,和相應的get,set方法。
需要匯入cglib-nodep-2.2.jar
been類
- <strong>public class CglibBean {
- /**
- * 實體Object
- */
- public Object object = null;
- /**
- * 屬性map
- */
- public BeanMap beanMap = null;
- public CglibBean() {
- super();
- }
- @SuppressWarnings("unchecked")
- public CglibBean(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;
- }
- @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));
- }
- return generator.create();
- }
- }
- </strong>
再寫一個測試類
- package com.infotech.cglibTest;
- import java.lang.reflect.Method;
- import java.util.HashMap;
- /**
- * Cglib測試類
- * @author cuiran
- * @version 1.0
- */
- public class CglibTest {
- @SuppressWarnings("unchecked")
- 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
- CglibBean bean = new CglibBean(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());
- }