How to get a caller class of a method

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

提交回复
热议问题