Java 如何在MethodInterceptor中获取方法的参数名?
我想在MethodInterceptor类上检索方法的参数名称Java 如何在MethodInterceptor中获取方法的参数名?,java,aop,Java,Aop,我想在MethodInterceptor类上检索方法的参数名称 public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); Class<?> declaringClass = method.getDeclaringClass(); Logger logger = LoggerFactory.getLogg
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();
}
public对象调用(MethodInvocation调用)抛出可丢弃的{
Method=invocation.getMethod();
Class declaringClass=方法.getDeclaringClass();
Logger Logger=LoggerFactory.getLogger(declaringClass);
//这里有一些治疗
返回调用。继续();
}
我就是找不到如何用MethodInvocation实例检索方法参数的名称。我不确定这是否可能……你不能。Java在运行时不保留参数名称,因此,拦截器(或反射api)无法获得该名称。
解决此问题的一种方法是将参数封装在一个类中,并使字段的名称与参数名称相对应。这是可能的,正如我在这里学到的: 下面是使用Spring ParameterNameDiscoveryr的示例:
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.");
}
这是一条路要走,只有几点意见:1。ParameterNameDiscoverer背后有几种策略来发现参数名称。2.如果您只想让参数名发现不需要任何额外的工作(例如添加注释等),则需要JDK8 3。使用JDK8时,使用javac的-parameters标志而不是-g(除非您确实需要完整的调试信息)