
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?
No comments:
Post a Comment