AspectJ pointcuts - get a reference to the joinpoint class and name

限于喜欢 提交于 2019-12-03 11:08:44

问题


I am using the @AspectJ style for writing aspects, to handle logging in our application. Basically I have a pointcut set up like so:

@Pointcut("call(public * com.example..*(..))")
public void logging() {}

and then a before and after advice like so:

@Before("logging()")
public void entering() {...}
...
@After("logging()")
public void exiting() {...}

I want to create a log in these methods in the following format:

logger.trace("ENTERING/EXITING [" className + "." + methodName "()]");

The problem is I don't know how to get a reference to the class and method names. I have tried:

joinPoint.getThis().getClass()

but this seems to return the caller's class name.

class A {
    public void a() {
        B.b();
    }
}


class B {
    public void b() {
        ...
    }
}

would result in the following log

ENTERING [A.b()]

can someone give some help on how to get the actual joinpoint class and method name


回答1:


You need to use joinPoint.getTarget().getClass(). Since you are using advising a call join point, the object of your interest is the target of the call.

Please note the API specification states:

Returns the target object. This will always be the same object as that matched by the target pointcut designator. Unless you specifically need this reflective access, you should use the target pointcut designator to get at this object for better static typing and performance.

Returns null when there is no target object.

Blindly using joinPoint.getTarget().getClass() can result in a NullPointerException. Consider using the join point's signature, such as:

final Signature signature = joinPoint.getSignature();

Then:

final Class clazz = signature.getDeclaringType();

Or if all you need is the class name:

final String clazz = signature.getDeclaringTypeName();



回答2:


    public void logBefore(JoinPoint joinPoint) {
    logger.info("###### Requested class : {} ; Method : {} ", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName());
    Object[] signatureArgs = joinPoint.getArgs();
    for (Object signatureArg : signatureArgs) {
        logger.info("###### Arguments: {} ", signatureArg.toString());
    }
} 

may help someone: Use above code to get the requested Class, method and args.



来源:https://stackoverflow.com/questions/5069293/aspectj-pointcuts-get-a-reference-to-the-joinpoint-class-and-name

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