Java: how to obtain the file name and row number in the source file

Source: Internet
Author: User

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/>}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.