6

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.

python
  • 1,870
  • 4
  • 24
  • 35
  • 1
    possible 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
  • 1
    Take 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 Answers1

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