cglib 是一个很强大的动态字节增强库, 使用例子:
cglib 官网:http://cglib.sourceforge.net/howto.html
public class Dao {
public void update(){
System.out.println("update");
}
public void insert(){
System.out.println("insert");
}
public void delete(){
System.out.println("delete");
}
}
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import net.sf.cglib.proxy.Enhancer;
public class Proxy implements MethodInterceptor{
public Object getObject(Class target){
Enhancer en=new Enhancer();
en.setSuperclass(target);
en.setCallback(this);
return en.create();
}
/**
* @param args
*/
public static void main(String[] args) {
Proxy proxy=new Proxy();
Dao dao=(Dao)proxy.getObject(Dao.class);
dao.delete();
}
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
System.out.println("before");
Object obj=arg3.invoke(arg0, arg2);
System.out.println("after");
return obj;
}
}
增加一个属性:
en.setStrategy(new DefaultGeneratorStrategy(){
@Override
protected ClassGenerator transform(ClassGenerator cg)
throws Exception {
AddPropertyTransformer add=new AddPropertyTransformer(new String[]{ "foo" },new Type[]{ Integer.TYPE });
return new TransformingClassGenerator(cg,add);
}
});
Cglib 入门
猜你喜欢
转载自duantonghai.iteye.com/blog/1106593
今日推荐
周排行