spring-bootreflectionproxy-classes

How to Method#getAnnotatedParameterTypes() in spring proxied class


I'm using spring-boot 2+ and created some custom annotation;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation{
}

When doing:

final AnnotatedType[] annotatedTypes = mostSpecificMethod.getAnnotatedParameterTypes();

//this will get the original class
//final Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);

Class<?> annotatedMappedClass = null;
for (AnnotatedType annotatedType : annotatedTypes) {
    if (annotatedType.isAnnotationPresent(MyCustomAnnotation.class)) {
        annotatedMappedClass = TypeFactory.rawClass(annotatedType.getType());
    }
}

it works when bean is not a proxy but when I add the @Transactional annotation it becomes a proxy and stops working. What is the Spring Util to find in the target class?


Solution

  • As far as I understood you'll need the bean. Using:

    Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass());
    

    seems to work.

    Also a more complex one:

        Method method = mostSpecificMethod;
        if (AopUtils.isAopProxy(bean)) {
            try {
                Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);
                method = clazz.getMethod(mostSpecificMethod.getName(), mostSpecificMethod.getParameterTypes());
            }
            catch (SecurityException ex) {
                ReflectionUtils.handleReflectionException(ex);
            }
            catch (NoSuchMethodException ex) {
                throw new IllegalStateException("...", ex);
            }
        }