动态代理性能比较

[b]转自http://javatar.iteye.com/blog/814426[/b]

//用javassit得到动态代理
public T createJavassistBytecodeDynamicProxy(LoadBalance loadBalance,ConcurrentMap<String, T> map,Class ifaces){
try{
ClassPool mPool = new ClassPool(true);
CtClass mCtc = mPool.makeClass(ifaces.getName() + "JavaassistProxy");
mCtc.addInterface(mPool.get(ifaces.getName()));
mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc));

mCtc.addField(CtField.make("public " + loadBalance.getClass().getName() + " sub;", mCtc));
mCtc.addField(CtField.make("public " + map.getClass().getName() + " map;", mCtc));
// mCtc.addField(CtField.make("public " + ArrayList.class.getName() + " list;", mCtc));

mCtc.addMethod(CtNewMethod.make("public Object getRealClient() { return (Object)sub.select(new "+ArrayList.class.getName()+"(map.values())); }",mCtc));

//获取接口的方法
for(Method method: ifaces.getMethods()){
Class returnType = method.getReturnType();
String modifiers = "public";
if(Modifier.PUBLIC==method.getModifiers()){
modifiers="public";
}else if(Modifier.PROTECTED==method.getModifiers()){
modifiers="protected";
}else if(Modifier.PRIVATE==method.getModifiers()){
modifiers="private";
}
Class<?>[] parameter = method.getParameterTypes();

String params = "";
String ps = "";
for(Class param:parameter){
params += param.getName()+" "+param.getName()+",";
ps+=param.getName()+",";
}
if(params.equals("")){
params = "";
ps="";
}else{
params=params.substring(0,params.length());
ps=ps.substring(0,ps.length());
}

mCtc.addMethod(CtNewMethod.make(modifiers +" void "+method.getName()+"(String a,String b){ Object t=this.getRealClient(); return (("+ifaces.getName()+")t)."+method.getName()+"(a,b) ;}", mCtc));
// mCtc.addMethod(CtNewMethod.make("public int count() { return delegate.count(); }", mCtc));
}


Class<?> pc = mCtc.toClass();

mCtc.debugWriteFile("/home/liguojun");
mCtc.writeFile("/home/liguojun");

T bytecodeProxy = (T) pc.newInstance();
Field filed = bytecodeProxy.getClass().getField("sub");
filed.set(bytecodeProxy, loadBalance);

Field filed1 = bytecodeProxy.getClass().getField("map");
filed1.set(bytecodeProxy, map);

return bytecodeProxy;
}catch (Exception e){
e.printStackTrace();
}
return null;

}


[b]注意:但写new ArrayList时无法识别,必须全写为字符串形式,即new ArrayList.class.getName(),return (("+ifaces.getName()+")t)为同理[/b]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值