How to take the file name and line number in the Java source code file:
In the C + + program, the compiler provides two macros to support the acquisition of line numbers and file names in the source file, the two macros are __file__,__line__
You can print line numbers and file names in the following ways
1.#include <stdio.h>
2.int main()
3.{
4. fprintf(stdout,"[%s:%d] Hello World!",__FILE__,__LINE__);
5. return 0;
6.}
But without these two macros in Java, how do we get the filename and line number, and flip through the JDK, we find the Stacktraceelement class. This class can be obtained from the throwable and can also be obtained from the thread class, through which I write the following test procedure for a print line number:
01.public class LineNo {
02. public static int getLineNumber() {
03. return Thread.currentThread().getStackTrace()[2].getLineNumber();
04. }
05.
06. public static String getFileName() {
07. return Thread.currentThread().getStackTrace()[2].getFileName();
08. }
09. public static void main(String args[]) {
10. System.out.println("["+getFileName()+":"+ getLineNumber()+"]"+"Hello World!");
11. }
12.}
Leaving a question, what does the magic number 2 in the above program mean?