如何通过 Java 中的反射获取方法参数的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7230326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:13:10  来源:igfitidea点击:

How to get the value of a method argument via reflection in Java?

javareflectionparametersannotationsarguments

提问by soc

Consider this code:

考虑这个代码:

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

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 @Fooannotation. (I know it is the third parameter of the parameter list.)

我对用@Foo. 假设我已经通过反射(with Method#getParameterAnnotations())弄清楚哪个方法参数具有@Foo注释。(我知道它是参数列表的第三个参数。)

How can I now retrieve the value of barfor further usage?

我现在如何检索 的值以bar供进一步使用?

回答by Sean Patrick Floyd

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 etc.)
  • Proxies (JDK, CGLib etc)
  • 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.

在所有这些中,您将从方法调用中收集参数,然后告诉方法调用执行。但是没有办法通过反射获取方法参数。

Update: here's a sample aspect to get you started using annotation-based validation with AspectJ

更新:这是一个示例方面,可让您开始在 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
    }

}