Frage

So, I have this class and I want to print which methods were called. When I run it it prints only trace and main but not method1 and method2. How can I change it so it would print method1 and method2, the methods called from main?

public class SomeClass
{
    public void method1() {}
    public void method2() {}

    public static void main(String args[]) throws Throwable 
    {
        SomeClass c = new SomeClass();
        c.method1();
        c.method2();
        SomeClass.trace();
    }

    public static void trace() throws Throwable
    {
        Throwable t = new Throwable();
        StackTraceElement[] stack = t.getStackTrace();
        for(StackTraceElement s : stack)
        System.out.println(s.getMethodName());
    }
}
War es hilfreich?

Lösung

method1 and method2 have been called but have completed their work, so there's no reason for them to be in the trace. A stack trace's job is to show you what functions are in progress (what calls are outstanding on the stack).

If you're looking for something that will tell you they were called (but have finished), the category of tool you're looking for is called a "code coverage" testing tool. That's not part of what the exception and stack trace aspects of the Java runtime are for.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top