Get the stack trace in Java without printing it

3

How can I get the stack trace at a position in the code when no exception was generated?

I come using

try
{
  // código
}
catch (IOException e)
{
  e.printStackTrace();
}

or even

e.getMessage()

within an exception, but I am interested to know if there is any way to obtain the stack trace in a specific part of the code, in order to be able to modify it as text, without generating an exception. For example, to show only the current method and the line. Is there a method to return it to me?

    
asked by Woody 06.01.2017 в 04:19
source

1 answer

4

You can run Thread.currentThread().getStackTrace() , what that will return an arrangement of StackTraceElement s that you can read and manipulate as you wish.

Example:

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for (StackTraceElement ste : stackTraceElements) {
    System.out.printf("%s.%s(%s:%s)%n",
            ste.getClassName(),
            ste.getMethodName(),
            ste.getFileName(),
            ste.getLineNumber());
}

Demo

    
answered by 06.01.2017 / 04:30
source