Search code examples
javaspringreflectionspring-aoptype-parameter

In around avice, how to get the 'type parameter' of a parameter of the advised method


With Spring AOP, I am writing an Aspect with an around advice that intercepts any method annotated with @MyAnnotation. Suppose the intercepted method was declared as follows,

@MyAnnotation
public String someMethod(ArrayList<Integer> arrList) {...}

In the advice method, I want to get infomation that the first parameter, i.e. arrList, has the type ArrayList with the type parameter Integer.

I have tried following this question by doing this

@Around("@annotation(MyAnnotation)")
public Object advice(ProceedingJoinPoint pjp) {
    Method method = ((MethodSignature) pjp.getSignature()).getMethod();
    Class<?>[] paramsClass = method.getParameterTypes();
    logger.info(((ParameterizedType) paramsClass[0].getGenericSuperclass()).getActualTypeArguments()[0])
    ...
}

But what was logged out is just an E. How shoud I do to so that it prints java.lang.Integer?


Solution

  • Try this:

    @Around("@annotation(MyAnnotation)")
    public Object advice(ProceedingJoinPoint pjp) throws Throwable {
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        Type[] genericParamsClass = method.getGenericParameterTypes();
    
        logger.info(((ParameterizedType) genericParamsClass[0]).getActualTypeArguments()[0]);
        ...
    }