How do I find the caller of a method using stacktrace or reflection?

后端 未结 12 1149
鱼传尺愫
鱼传尺愫 2020-11-21 13:26

I need to find the caller of a method. Is it possible using stacktrace or reflection?

12条回答
  •  日久生厌
    2020-11-21 13:40

    use this method:-

     StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
     stackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
     System.out.println(e.getMethodName());
    

    Caller of method example Code is here:-

    public class TestString {
    
        public static void main(String[] args) {
            TestString testString = new TestString();
            testString.doit1();
            testString.doit2();
            testString.doit3();
            testString.doit4();
        }
    
        public void doit() {
            StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
            StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
            System.out.println(e.getMethodName());
        }
    
        public void doit1() {
            doit();
        }
    
        public void doit2() {
            doit();
        }
    
        public void doit3() {
            doit();
        }
    
        public void doit4() {
            doit();
        }
    }
    

提交回复
热议问题