How to get a caller class of a method

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

提交回复
热议问题