How can I inspect the call stack at run-time?

Sandip Chitale

You cannot as such. However you can get the names of the classes, method names (without parameter names), Source file name + line number (only if JIT is off). It works on most of the implementations of JDKs, if the debug information is still in the class files (i.e. it has not been stripped out).

It exploits the fact that the java.lang.Throwable class has the following method -

public void printStackTrace(PrintStream s)

The above method captures the stack where the Throwable is created -

Here is a simpe program and its output -

 * StackTrace.java
 * Created: Sun Aug 27 08:09:21 2000
 * @author Sandip Chitale (schitale@selectica.com)
 * @version
import java.io.*;

public class StackTrace {
	private static void stackTrace() 
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		new Throwable().printStackTrace(pw);
	public static void main(String[] args) {
} // StackTrace

Output -

	at StackTrace.stackTrace(StackTrace.java:18)
	at StackTrace.main(StackTrace.java:23)

Using the same principle you could capture the stack trace and extract relevent information from it. You could encapsulate the functionality in a Class. The Source file name and line number are only available if the JIT compiler is off.

You could get the Class objects whose methods are on the stack by using the static private method -


which you can invoke in secure environment using reflection to find the corresponding (to 'getClassContext()) java.lang.reflect.Method object and the calling setAccesible(true) on it and then calling invoke(nuu, new Object[0]) on it.

You could get the full information using the JVMDI (java virtual machine debugging interface) in debug mode- http://java.sun.com/products/jpda/