How to get a caller class of a method

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

提交回复
热议问题