goole guice Aop 获取参数值

2018-11-01 14:18:19 +08:00
 jasondeepy
最近在想写一个 Aop 给公共接口做限制,项目是基于 guice 的,在写的过程中集合了 Javassit 这个包,底层是动态代理和反射,但是在获取参数值的过程中,走到其中可以一步时会报错,代码如下:

public Object invoke(MethodInvocation invocation) throws Throwable {
Object[] args = invocation.getArguments();

//全路径名
Class<?> clazz = invocation.getThis().getClass();
String clazzName = clazz.getName();
//获取方法名称
String methodName = invocation.getMethod().getName();

//获取参数名称和值
Map<String,Object > nameAndArgs = this.getFieldsName(this.getClass(),clazzName, methodName,args);
System.out.println("参数名和值:" + nameAndArgs.toString());

//动态的获取 PageSize
//Integer pageSize =Integer.parseInt(redisCli.get("pagesize"));

int pageSize = 50;
if(nameAndArgs !=null && nameAndArgs.size()>0){
Integer pagesize = (Integer) nameAndArgs.get("pagesize");
if(pagesize <= pageSize && pagesize >0){
//满足条件放行
return invocation.proceed();
}
//不满足就不调用方法
return null;
}
//无参数放行
return invocation.proceed();
}

//需用到 javassit 包
private Map getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
Map map = new HashMap();
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get(clazzName);------这步会报错------
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
System.out.println(cc);
//接口全路径
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
UMSLogger.info("*** PaginationHelper attr is null === ");
return null;
}
// String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < cm.getParameterTypes().length; i++) {
//paramNames 即参数名
map.put(attr.variableName(i + pos), args[i]);
}
return map;
}
1216 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/503397

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX