Knowing caller class with AspectJ

牧云@^-^@ 提交于 2019-12-05 16:23:43

You can determine which class is invoking the current method with the following call. Note that you'll have to catch ClassNotFoundException (unless you're satisfied simply retrieving the name as a String).

Class.forName(Thread.currentThread().getStackTrace()[2].getClassName());

Why the third element? Because the stack is ordered like so when the stack trace method is invoked:

  1. Thread#getStackTrace()
  2. CurrentClass.currentMethod()
  3. ParentClass.parentMethod()

Actually cheeken's answer is nice, but for AspectJ call() pointcuts you can get the calling class much more easily and without ugly reflection:

thisEnclosingJoinPointStaticPart.getSignature().getDeclaringType()

Please consider to accept this answer if you think it is better than the other one, otherwise just enjoy the power of AspectJ. ;-)

This is an alternative that seems more light since is native and commonly used by the SecurityManager. To use it we need a utility class because the the method we need is protected.

public class CallStackUtils extends SecurityManager {

  static CallStackUtils sm = new CallStackUtils();

  public Class[] getCallersClassesStack0() {
    return getClassContext();
  }

  static public Class[] getCallersClassesStack() {
    return sm.getCallersClassesStack0();
  }

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