How to obtain the file name and line number in the Java source code file :)
In the C/C ++ program, the compiler provides two macros to obtain the row number and file name in the source file. The two macros are _ file __,__ line __
You can print the row number and file name in the following method:
# Include <stdio. h> <br/> int main () <br/> {<br/> fprintf (stdout, "[% s: % d] Hello world! ",__ File __,__ line _); <br/> return 0; <br/>}
But there are no these two Macros in Java, so how do we get the file name and row number? Read JDK and find the stacktraceelement class. This class can be obtained from throwable, or from the Thread class, through which I write the following test program to print the row number:
Public class lineno {<br/> Public static int getlinenumber () {<br/> return thread. currentthread (). getstacktrace () [2]. getlinenumber (); <br/>}< br/> Public static string getfilename () {<br/> return thread. currentthread (). getstacktrace () [2]. getfilename (); <br/>}< br/> Public static void main (string ARGs []) {<br/> system. out. println ("[" + getfilename () + ":" + getlinenumber () + "]" + "Hello world! "); <Br/>}< br/>}