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

后端 未结 1 1978
情歌与酒
情歌与酒 2020-12-09 11:52

Consider this code:

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

I\'m interested in the value of the argument annot

相关标签:
1条回答
  • 2020-12-09 12:02

    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)

    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

    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
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题