How to get call hierarchy in java

Anish Antony picture Anish Antony · Nov 7, 2013 · Viewed 8.9k times · Source

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

Answer

Jason C picture Jason C · Nov 7, 2013

See the documentation for Thread.

In particular, Thread.currentThread().getStackTrace() retrieves information about the trace, and Thread.dumpStack() prints the current stack trace.

There's no need for weird hacks with Exception or anything.