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

Consider this code:

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

I'm interested in the meaning of an argument annotated with @Foo . Suppose I already understood through reflection (with Method#getParameterAnnotations() ), the method parameter has an @Foo annotation. (I know this is the third parameter of the parameter list.)

How can I now get the bar value for future use?

+6
source share
1 answer

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

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

  • AOP (AspectJ / Spring AOP, etc.)
  • Proxies (JDK, CGLib, etc.)

In all of these cases, you must collect the parameters from the method call, and then pass the method call to execute. But there is no way to get the method parameters through reflection.

Update: here's an example aspect for you to start using annotation-based validation using 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 } } 
+11
source

Source: https://habr.com/ru/post/896123/


All Articles