Core Java: How To Get Java Source Code Line Number & File Name in Code
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?
Filed under Headline News, How To, Java Software, Open Source Software, Programming |
|
RSS 2.0 |
Trackback this Article
|
Email this Article
You may also like to read |





































September 8th, 2008 at 7:46 am
If you’re coding in Eclipse, you can use “systrace” to print out the Class.Method().
September 9th, 2008 at 4:42 am
Java is still alive ?
September 9th, 2008 at 7:42 am
Is trolling still alive?
September 15th, 2008 at 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 15th, 2008 at 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:
September 15th, 2008 at 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
dumpThreads
java.lang.Thread
getStackTrace
com.bharat.SimpleTest
main
Third element is where ‘Thread.currentThread().getStackTrace()’ is called.
so we are using the number 2
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.
September 15th, 2008 at 9:15 pm
That is correct. As the code is within a method we need to use the stacktrace element of the calling code.