利用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 propertyMap) {
super();
this.object = this.generateBean(propertyMap);
this.beanMap = BeanMap.create(this.object);
}

private Object generateBean(Map propertyMap) {
BeanGenerator beanGenerator = new BeanGenerator();
for (Map.Entry 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 propertyMap=new HashMap();
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对象;用这个实现.然后根据自己的业务逻辑改造
这个类就行了
 

你可能感兴趣的:(java基础)