How to get a caller class of a method

前端 未结 4 1523
渐次进展
渐次进展 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: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.

提交回复
热议问题