利用cglib庫給物件動態新增屬性
阿新 • • 發佈:2019-01-04
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物件;用這個實現.然後根據自己的業務邏輯改造
這個類就行了 轉發至微博 轉發至微博