How Java takes the file name and line number from the source file

Source: Internet
Author: User
Tags thread thread class

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?

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.