AspectJ 切入点 - 获取对连接点类和名称的引用 [英] AspectJ pointcuts - get a reference to the joinpoint class and name

查看:34
本文介绍了AspectJ 切入点 - 获取对连接点类和名称的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用@AspectJ 风格来编写方面,以处理我们应用程序中的日志记录.基本上我有一个像这样设置的切入点:

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() {
        ...
    }
}

会导致以下日志

ENTERING [A.b()]

有人可以就如何获取实际的连接点类和方法名称提供一些帮助

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

推荐答案

您需要使用 joinPoint.getTarget().getClass().由于您使用的是通知呼叫加入点,因此您感兴趣的对象是呼叫的目标.

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.

请注意API 规范说明:

返回目标对象.这将始终与目标切入点指示符匹配的对象相同.除非您特别需要这种反射访问,否则您应该使用目标切入点指示符来获取此对象以获得更好的静态类型和性能.

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.

没有目标对象时返回null.

盲目使用joinPoint.getTarget().getClass() 会导致NullPointerException.考虑使用连接点的签名,例如:

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

final Signature signature = joinPoint.getSignature();

那么:

final Class clazz = signature.getDeclaringType();

或者如果您只需要类名:

Or if all you need is the class name:

final String clazz = signature.getDeclaringTypeName();

这篇关于AspectJ 切入点 - 获取对连接点类和名称的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆