-
enhancer.setNamingPolicy //字节码生成器 enhancer.setStrategy enhancer.setSuperclass enhancer.setInterfaces //设置方法拦截器映射:哪个方法的调用转发到哪个拦截器 enhancer.setCallbackFilter enhancer.setCallbackTypes //方法在构造方法中被调用时是否被拦截,默认是 enhancer.setInterceptDuringConstruction // 设置多个拦截器 enhancer.setCallbacks
//基本使用
Enhancer enhancer = new Enhancer();
//代理类继承AppConfig类
enhancer.setSuperclass(AppConfig.class);
//设置拦截器
enhancer.setCallback(new MyMethodInterceptor());
//创建bean
AppConfig o = (AppConfig) enhancer.create();
o.say();
//每次调用代理类的方法都会进入这个拦截器
public class MyMethodInterceptor implements MethodInterceptor {
//o-被代理对象,代理类的父类
//method-被代理类的方法
//objects-参数
//methodProxy-代理类的方法
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("前");
//methodProxy.invokeSuper调用代理类父类的方法
//不能是method.invoke
Object invokeSuper = methodProxy.invokeSuper(o, objects);
return invokeSuper;
}
}
上面是基本使用方法。
使用BeanGenator动态的生成类,并给类添加属性
BeanGenerator beanGenerator = new BeanGenerator();
beanGenerator.setSuperclass(AppConfig.class);
//这里是给生成类添加一个属性,并且指定属性的类型是String
beanGenerator.addProperty("aaa",String.class);
AppConfig appConfig = (AppConfig)beanGenerator.create();
appConfig.say();
BeanGenator不能设置callback,也不能设置值
用BeanMap动态的生成类,并给类添加属性
// 初始化
BeanMap map = BeanMap.create(new Pojo());
// 构造
Pojo pojo = new Pojo();
pojo.setIntValue(1);
pojo.setBigInteger(new BigInteger("2"));
// 赋值
map.setBean(pojo);
// 验证
System.out.println(map.get("intValue"));
System.out.println(map.keySet());
System.out.println(map.values());
- 避免每次进行BeanMap map = BeanMap.create();创建对象,不同于BeanCopier对象,BeanMap主要针对对象实例进行处理,所以一般建议是map.setBean(pojo);进行动态替换持有的对象实例。
- 应用场景:针对put,putAll操作会直接修改pojo对象里的属性,所以可以通过beanMap.putAll(map)进行map<->pojo属性的拷贝。