如何通过在Java反射得到一个方法参数的值? [英] How to get the value of a method argument via reflection in Java?

查看:378
本文介绍了如何通过在Java反射得到一个方法参数的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个code:

public void example(String s, int i, @Foo Bar bar) {
    /* ... */
}

我感兴趣的是与 @foo 批注的参数的值。假设我已经通过反射想通了(与方法#getParameterAnnotations())的方法参数的 @foo 注解。 (我知道这是参数列表的第三个参数。)

I'm interested in the value of the argument annotated with @Foo. Assume that I have already figured out via reflection (with Method#getParameterAnnotations()) which method parameter has the @Foo annotation. (I know it is the third parameter of the parameter list.)

我怎么能现在进一步使用检索的价值?

How can I now retrieve the value of bar for further usage?

推荐答案

您不能。反射不具有访问本地变量,包括方法参数。

You can't. Reflection does not have access to local variables, including method parameters.

如果你想要的功能,你需要拦截方法调用,您可以在几种方式之一进行:

If you want that functionality, you need to intercept the method call, which you can do in one of several ways:


  • AOP(AspectJ的/ Spring AOP的等)

  • 代理(JDK,CGLIB等)

在所有这些,你会收集来自方法调用的参数,然后告诉方法调用执行。但有没有办法让在通过反射方法的参数。

In all of these, you would gather the parameters from the method call and then tell the method call to execute. But there's no way to get at the method parameters through reflection.

更新:这里是一个示例方面您开始使用使用AspectJ基于注解的验证

Update: here's a sample aspect to get you started using annotation-based validation with 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
    }

}

这篇关于如何通过在Java反射得到一个方法参数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆