How do I find the caller of a method using stacktrace or reflection?

后端 未结 12 1144
鱼传尺愫
鱼传尺愫 2020-11-21 13:26

I need to find the caller of a method. Is it possible using stacktrace or reflection?

12条回答
  •  盖世英雄少女心
    2020-11-21 13:39

    Java 9 - JEP 259: Stack-Walking API

    JEP 259 provides an efficient standard API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces. Before Stack-Walking API, common ways of accessing stack frames were:

    Throwable::getStackTrace and Thread::getStackTrace return an array of StackTraceElement objects, which contain the class name and method name of each stack-trace element.

    SecurityManager::getClassContext is a protected method, which allows a SecurityManager subclass to access the class context.

    JDK-internal sun.reflect.Reflection::getCallerClass method which you shouldn't use anyway

    Using these APIs are usually inefficient:

    These APIs require the VM to eagerly capture a snapshot of the entire stack, and they return information representing the entire stack. There is no way to avoid the cost of examining all the frames if the caller is only interested in the top few frames on the stack.

    In order to find the immediate caller's class, first obtain a StackWalker:

    StackWalker walker = StackWalker
                               .getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
    

    Then either call the getCallerClass():

    Class callerClass = walker.getCallerClass();
    

    or walk the StackFrames and get the first preceding StackFrame:

    walker.walk(frames -> frames
          .map(StackWalker.StackFrame::getDeclaringClass)
          .skip(1)
          .findFirst());
    

提交回复
热议问题