How to get a caller class of a method

前端 未结 4 1520
渐次进展
渐次进展 2021-01-16 10:36

How do I know which class called a method?

class A {
   B b = new B();

   public void methodA() {
    Class callerClass = b.getCallerCalss(); // it should b         


        
相关标签:
4条回答
  • 2021-01-16 11:22

    You can get the class name of the caller class by fetching the second element of the stack trace:

    final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    System.out.println(stackTrace[1].getClassName());
    

    The getClassName method of the StackTraceElement class returns with a String so you won't get a Class object unfortunately.

    0 讨论(0)
  • 2021-01-16 11:25

    There's a method of observing the stacktrace

    StackTraceElement[] elements = Thread.currentThread().getStackTrace()
    

    Javadoc

    The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

    0 讨论(0)
  • 2021-01-16 11:26

    This is easily done with Thread.currentThread().getStackTrace().

    public static void main(String[] args) {
        doSomething();
    }
    
    private static void doSomething() {
        System.out.println(getCallerClass());
    }
    
    private static Class<?> getCallerClass() {
        final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        String clazzName = stackTrace[3].getClassName();
        try {
            return Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    

    [3] is used because [0] is the element for Thread.currentThread(), [1] is for getCallerClass, [2] is for doSomething, and finally, [3] is main. If you put doSomething in another class, you'll see it returns the correct class.

    0 讨论(0)
  • 2021-01-16 11:33

    Try Throwable.getStackTrace().

    Create a new Throwable.. you don't have to throw it :).

    untested:

    Throwable t = new Throwable();
    StackTraceElement[] es = t.getStackTrace();
    // Not sure if es[0] would contain the caller, or es[1]. My guess is es[1].
    System.out.println( es[0].getClass() + " or " + es[1].getClass() + " called me.");
    

    Obviously if you're creating some function (getCaller()) then you'll have to go another level up in the stack trace.

    0 讨论(0)
提交回复
热议问题