如何在MethodInterceptor中获取方法的参数名称?

时间:2011-06-02 18:03:46

标签: java aop

我想在MethodInterceptor类上检索参数的方法名称。

public Object invoke(MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    Class<?> declaringClass = method.getDeclaringClass();
    Logger logger = LoggerFactory.getLogger(declaringClass);
    //here some treatment
    return invocation.proceed();
}

我只是找不到如何用MethodInvocation实例检索方法参数的名称。我不确定它是否可能......

2 个答案:

答案 0 :(得分:2)

你做不到。 Java没有在运行时保留param名称,因此,拦截器(或反射api)无法获得它。 解决此问题的一种方法是将params包装在一个类中,并使字段的名称与您的param名称相对应。

答案 1 :(得分:1)

可能,正如我在此处学到的那样:Getting the name of a method parameter

以下是使用String ParameterName Discoverer的示例:

private Object getParameterName(Method specificMethod, int i) {
    // Project needs to be build with a -g (debug) option to contain information about parameter names.
    ParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();

    String parameterName = discoverer.getParameterNames(specificMethod)[i];
    if (parameterName != null) {
        return parameterName;
    }
    throw new IllegalArgumentException("Unable to determine parameter name. Please build the project with -g (debug) option.");
}