How can I find out the name of the source file, the line number within that source file, and the name of the method that is excuting?

Sandip Chitale

The following 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 javax.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 simple 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.

Note that the source file name and line number are only available if the JIT compiler is off (since, typically, JIT compilation doesn't carry that information along).

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact