Java - Get to stack frames of a thread.

Introduction

A Throwable object captures the stack of the thread at the point it is created.

To capture the snapshot of the stack of a thread at a different point where the Throwable object was created, call the fillInStackTrace().

Demo

public class Main {
  public static void main(String[] args) {
    m1();//from  w w w.j a va  2s . c o m
  }

  public static void m1() {
    m2();
  }

  public static void m2() {
    m3();
  }

  public static void m3() {
    Throwable t = new Throwable();

    StackTraceElement[] frames = t.getStackTrace();

    printStackDetails(frames);
  }

  public static void printStackDetails(StackTraceElement[] frames) {
    System.out.println("Frame count: " + frames.length);

    for (int i = 0; i < frames.length; i++) {
      // Get frame details
      int frameIndex = i; // i = 0 means top frame
      String fileName = frames[i].getFileName();
      String className = frames[i].getClassName();
      String methodName = frames[i].getMethodName();
      int lineNumber = frames[i].getLineNumber();

      // Print frame details
      System.out.println("Frame Index: " + frameIndex);
      System.out.println("File Name: " + fileName);
      System.out.println("Class Name: " + className);
      System.out.println("Method Name: " + methodName);
      System.out.println("Line Number: " + lineNumber);
    }
  }
}

Result

Related Topic