Getting a Template/Generic java.lang.reflect.Method object from org.aspectj.lang.ProceedingJoinPoint

会有一股神秘感。 提交于 2019-12-06 07:10:44
Bozho
MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();
Method targetMethod = methodSignature.getMethod();

This is not immediately obvious, for which the API is to blame.

Also see Spring AOP: how to get the annotations of the adviced method. I haven't tested this myself. The OP there says it solved the issue for him. For another use an additional @Around(annotation...) annotation was needed. (Try setting the target to be only METHOD for example and see how it behaves)

Okay I have now my problem solved. After a closer look at what: methodSignature.getMethod() returns I noticed it returned the interface instead of the implementing class, and of course there were no annotations on the interface. This is different from EJB interceptors where getMethod() returns the implementing class method.

So the final solution is this:

    final String methodName = pjp.getSignature().getName();
    final MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
    Method method = methodSignature.getMethod();
    if (method.getDeclaringClass().isInterface()) {
        method = pjp.getTarget().getClass().getDeclaredMethod(methodName, method.getParameterTypes());    
    }

and if you like, you can handle interface annotations here as well, if needed.

Also notice this bit: method.getParameterTypes() without this it would still throw NoSuchMethodException so it's a good thing we could get the correct signature via ((MethodSignature)pjp.getSignature()).getMethod();

Hopefully, no more surprises, even though I am not happy about using reflection here, I would just prefer to have the method instance of the implementing class, as in InvocationContext of EJB.

BTW, Spring's native approach without AspectJ:

public Object invoke(final MethodInvocation invocation) throws Throwable {}

returns interface and not implementing class as well. Checked it for the sake of knowledge too.

Best Regards and thanks for helping, I really appreciate it. Oleg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!