guice-aop get mathods and parameters

37 views
Skip to first unread message

周慎之

unread,
Oct 29, 2018, 12:00:19 PM10/29/18
to google-guice
how to  get mathods and parameters by guice-aop?

周慎之

unread,
Oct 30, 2018, 8:02:45 AM10/30/18
to google-guice
public class PageIntercepter implements MethodInterceptor {

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

        //全路径名
        String classType = invocation.getThis().getClass().getName();------------this line is wrong,but idont know how to get classType-------------
        Class<?> clazz = Class.forName(classType);
        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();
        ClassClassPath classPath = new ClassClassPath(cls);
        pool.insertClassPath(classPath);
        CtClass cc = pool.get(clazzName);
        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;
    }
}

在 2018年10月30日星期二 UTC+8上午12:00:19,周慎之写道:
Reply all
Reply to author
Forward
0 new messages