Core Java: How To Get Java Source Code Line Number & File Name in Code
By Angsuman Chakraborty, Gaea News NetworkMonday, September 8, 2008
While debugging code Java programmers often use System.out.println(). It is important to write separate message in each System.out.println() so you can understand from the output where the problem lies.
Now it is time-consuming and somewhat tedious to invent new message for each System.out.println() debug message. What if you could call methods which allows you to print the current file name and line number?
That would automatically ensure unique message in every System.out.println(). Also it will help you to immediately pinpoint the offending code. You can copy-paste something like this anywhere in your code (embellish it with more topical information as needed) and be able to pinpoint its location:
System.out.println(getFileName() + “:” + getClassName() + “:” + getMethodName() + “:” + getLineNumber());
I will show the implementation of getLineNumber() below and leave the rest as an exercise:
/** Get the current line number.
* @return int - Current line number.
*/
public static int getLineNumber() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
Have you noticed the magic number - 2? Can you explain it?
Tags: Core Java, Java Programming, Lies, Programming
Don |
Arlando Bloom |
June 29, 2009: 12:59 am
Thanks for this wonderful addition. Really enjoyed your article. Appreciate people taking the time to write quality work. The |
iamy |
June 11, 2009: 9:53 am
I would like to know about following given code import java.*.* |
sravan |
September 15, 2008: 9:15 pm
That is correct. As the code is within a method we need to use the stacktrace element of the calling code. |
Bharat Kondeti |
September 15, 2008: 1:34 pm
This is what I understood Java Doc for ‘getStackTrace’ ‘If the returned array is of non-zero length then the first element of the array represents the top of the stack, which is the most recent method invocation in the sequence.’ when I print class name and method name for all the stackTraceElements for current thread java.lang.Thread java.lang.Thread com.bharat.SimpleTest Third element is where ‘Thread.currentThread().getStackTrace()’ is called. I believe by using the above statement we are accessing the Exception stack trace which would have been thrown if an exception would had occurred. |
Mark O'Connor |
September 15, 2008: 7:34 am
Enabling debug when compiling the Java code will also help to understand where an exception is being thrown from in a java stack trace/ The following is the ANT “javac” task: |
Shubhashish |
September 15, 2008: 3:25 am
Probably first is the Main calling class itself and other is the other which we want to debug … I am not sure |
September 8, 2008: 7:46 am
If you’re coding in Eclipse, you can use “systrace” to print out the Class.Method(). |
Content-based image retrieval