如何通过Java中的反射获取方法参数的值? [英] How to get the value of a method argument via reflection in Java?

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

问题描述

考虑这个代码:

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

我对用 @Foo 注释的参数的值感兴趣.假设我已经通过反射(使用 Method#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.)

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

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天全站免登陆