如何通过Java中的reflection获取方法参数的值?
考虑以下代码:
public void example(String s, int i, @Foo Bar bar) { /* ... */ }
我对用@Foo
注释的参数的值感兴趣。 假设我已经通过reflection(使用Method#getParameterAnnotations()
)找出了哪个方法参数具有@Foo
注释。 (我知道它是参数列表的第三个参数。)
我现在如何检索bar
的值以供进一步使用?
你不能。 Reflection无法访问局部变量,包括方法参数。
如果您需要该function,则需要拦截方法调用,您可以通过以下几种方式之一来执行此操作:
- AOP(AspectJ / Spring AOP等)
- 代理(JDK,CGLib等)
在所有这些中,您将从方法调用中收集参数,然后告诉方法调用执行。 但是没有办法通过reflection获得方法参数。
更新:这是一个示例方面,可帮助您开始使用AspectJ进行基于注释的validation
public aspect ValidationAspect { pointcut serviceMethodCall() : execution(public * com.yourcompany.**.*(..)); Object around(final Object[] args) : serviceMethodCall() && args(args){ Signature signature = thisJoinPointStaticPart.getSignature(); if(signature instanceof MethodSignature){ MethodSignature ms = (MethodSignature) signature; Method method = ms.getMethod(); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); String[] parameterNames = ms.getParameterNames(); for(int i = 0; i < parameterAnnotations.length; i++){ Annotation[] annotations = parameterAnnotations[i]; validateParameter(parameterNames[i], args[i],annotations); } } return proceed(args); } private void validateParameter(String paramName, Object object, Annotation[] annotations){ // validate object against the annotations // throw a RuntimeException if validation fails } }