1. 程式人生 > >利用cglib庫給物件動態新增屬性

利用cglib庫給物件動態新增屬性

package com.lrq.cglib;

import java.util.Map;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

public class DynamicGenerateBean {

private Object object;

private BeanMap beanMap;

public DynamicGenerateBean(Map<String, Class> propertyMap) {
super();
this.object = this.generateBean(propertyMap);
this.beanMap = BeanMap.create(this.object);
}

private Object generateBean(Map<String, Class> propertyMap) {
BeanGenerator beanGenerator = new BeanGenerator();
for (Map.Entry<String, Class> me : propertyMap.entrySet()) {
// 給bean添 屬性;即屬性對應的型別;
beanGenerator.addProperty(me.getKey(), me.getValue());
}
return beanGenerator.create();
}

public void setPropertyByName(String propertyName, Object value) {
this.beanMap.put(propertyName, value);
}

public Object getPropertyByName(String propertyName) {
return this.beanMap.get(propertyName);
}

}

測試類:
package com.lrq.cglib;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class DynamicGenerateBeanTest {
@SuppressWarnings({ "unused", "rawtypes" })
@Test
public void test(){

Map<String, Class> propertyMap=new HashMap<String, Class>();
propertyMap.put("id", Integer.class);
propertyMap.put("name", String.class);
//propertyMap.put("",int.class);
DynamicGenerateBean dynamicGenerateBean=new DynamicGenerateBean(propertyMap);
dynamicGenerateBean.setPropertyByName("id", 1);
dynamicGenerateBean.setPropertyByName("name", "lirongqiang");
System.out.println(dynamicGenerateBean.getPropertyByName("id"));
System.out.println(dynamicGenerateBean.getPropertyByName("name"));
//System.out.println(dynamicGenerateBean.getPropertyByName("id"));
}
}

他實現了動態給某個物件新增屬性並設定值:但是並不是真正意義上的給屬性動態新增屬性,只是實現了這種效果而已;
應用場景:vo物件,當我們給vo物件賦值的時候可以採用這種方法,不需要每次都建立vo物件;用這個實現.然後根據自己的業務邏輯改造
這個類就行了 microblog.png?1 轉發至微博 microblog.png?1 轉發至微博