Search code examples
javastack-tracecall-hierarchy

How to get call hierarchy in java


I have three classes named FirstClass,SecondClass and ThirdClass. Here follows the source of three classes:

FirstClass.java

public class FirstClass {
    public void firstMethod(){
        SecondClass secondClass = new SecondClass();
        secondClass.secondMethod();
    }
    public static void main(String[] args) {
        FirstClass firstClass = new FirstClass();
        firstClass.firstMethod();
    }

}

SecondClass.java

public class SecondClass {
    public void secondMethod(){
        ThirdClass thirdClass = new ThirdClass();
        thirdClass.thirdMethod();
    }

}

ThirdClass.java

public class ThirdClass {
    public void thirdMethod(){
        System.out.println("Here i need to print where the call comes from,(call hierarchy) Is it possible?");
    }
}

On the final method(here it is ThirdClass.thirdMethod()) i need to print where the method call comes from (I mean the call hierarchy). So what i need to write in thirdMethod() for that


Solution

  • Try something like this to access the stack of your current thread:

    Thread.currentThread().getStackTrace();
    

    This returns an array of StackTraceElement which you then can print or check or do whatever you want.

    However, be careful here: If your method behaves differently depending on the caller of your method (e.g by analyzing the stack and reacting on it), you can create some really uncommon and unexpected behaviour for anybode using code like this.