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.
Asked
Active
Viewed 2,780 times
6
-
1possible duplicate of [How to get source file-name/line-number from a java.lang.Class object](http://stackoverflow.com/questions/7483421/how-to-get-source-file-name-line-number-from-a-java-lang-class-object) – William Price Dec 19 '14 at 04:03
-
1Take a look at using [Apache logging](http://logging.apache.org/log4j/2.0/manual/layouts.html) services, which allows you to specify a file and line number (among other pieces of info) in a log format, which can be printed to the screen or written to a file. – Ryan J Dec 19 '14 at 04:05
-
William Price, Thanks for you information, very useful – python Dec 19 '14 at 04:26
1 Answers
6
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)

Elliott Frisch
- 198,278
- 20
- 158
- 249
-
1
-
-
@dkatzel It's a way to get current file name and line number; I speak not as to its' efficiency. – Elliott Frisch Dec 19 '14 at 04:19
-
System.out.println(Thread.currentThread().getStackTrace()[1]); I have tested this, it seems this will scan the call stack, which doesn't performance as good as I expect – python Dec 19 '14 at 04:25