How can I inspect the call stack at run-time?
Created May 4, 2012
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); System.out.println(sw.toString()); } public static void main(String[] args) { stackTrace(); } } // StackTrace Output - java.lang.Throwable 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 -
java.util.ResourceBundle.getClassContext()
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/