考虑以下代码:如何通过Java中的反射获取方法参数的值?
public void example(String s, int i, @Foo Bar bar) {
/* ... */
}
我感兴趣的是与@Foo
注释的参数的值。假设我已经通过反思(与Method#getParameterAnnotations()
)计算出哪个方法参数具有@Foo
注释。 (我知道它是参数列表的第三个参数)。
我现在如何检索bar
的值以进一步使用?
考虑以下代码:如何通过Java中的反射获取方法参数的值?
public void example(String s, int i, @Foo Bar bar) {
/* ... */
}
我感兴趣的是与@Foo
注释的参数的值。假设我已经通过反思(与Method#getParameterAnnotations()
)计算出哪个方法参数具有@Foo
注释。 (我知道它是参数列表的第三个参数)。
我现在如何检索bar
的值以进一步使用?
你不能。反射无法访问局部变量,包括方法参数。
如果你想要的功能,你需要拦截方法调用,您可以在几种方式之一:
在所有这些,你会从方法调用收集参数,然后告诉方法调用执行。但是没有办法通过反射来获取方法参数。
更新:这里有一个样品方面让您开始使用使用AspectJ
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
}
}
我已经在使用AspectJ,但我还没有找到办法。这是以前的问题:http://stackoverflow.com/questions/7228590/how-to-check-if-a-parameter-of-the-current-method-has-an-annotation-and-retrieve – soc
@soc好的,看看我的最新动态,购买[AspectJ in Action](http://www.manning.com/laddad2/),真正学会如何去做(或者在[AspectJ用户列表](http:///www.eclipse.org/aspectj/userlists.php) –
嘿,谢谢!:-)我已经购买了这本书,但我试图把所有内容都放入匹配签名中,但这并不奏效...... – soc
基于注解的验证我不明白的问题。 'bar'的值只在运行时才可用。你想拦截调用'example'吗?或者你的意思是数据类型“Bar”? – home