最近在想写一个 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;
}