Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way that Java could get current file name and current line number?

Tags:

java

file

logging

In C++, the file of the source code and current line number is decided by FILE and INLINE, which is decided at compiling time, is there any method in Java that could do the similar thing? The file and line number is decided at compiling time instead of runtime? this will be convenient for log. I kind of doubt that use runtime method to detect these information will decrease the performance.

like image 875
python Avatar asked Dec 19 '14 03:12

python


People also ask

How to read individual lines from a file Java?

Using the Java BufferedRedaer class is the most common and simple way to read a file line by line in Java. It belongs to java.io package. Java BufferedReader class provides readLine() method to read a file line by line.

What is the name of the property used to fetch line numbers method names?

getStackTrace() , one can get the line number of an StackTraceElement .

Can Java files have numbers?

1. Number of classes in a Java source file: A Java program can contain any number of classes, and at most, one of them can be declared as a public class.


Video Answer


1 Answers

You could use Thread.getStackTrace() and something like

System.out.println(Thread.currentThread().getStackTrace()[1]);

Output includes the current method and line number (if debugging was compiled in). For example,

com.stackoverflow.Main.main(Main.java:23)
like image 185
Elliott Frisch Avatar answered Oct 25 '22 19:10

Elliott Frisch