V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
jasondeepy
V2EX  ›  程序员

goole guice Aop 获取参数值

  •  
  •   jasondeepy · 2018-11-01 14:18:19 +08:00 · 1189 次点击
    这是一个创建于 1995 天前的主题,其中的信息可能已经有所发展或是发生改变。
    最近在想写一个 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;
    }
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5252 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 05:52 · PVG 13:52 · LAX 22:52 · JFK 01:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.