Is there a way Java can get the current filename and current line number?

In C ++ the source code file and the current line number is defined by FILE and INLINE , which is defined at compile time, is there any method in Java that could do this? Is file and line number determined at compile time instead of runtime? it will be convenient for the magazine. I doubt that using the runtime method to detect this data will result in performance degradation.

+3


source to share


1 answer


You can use Thread.getStackTrace()

something like

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

      



The output includes the current method and line number (if debug was compiled). For example,

com.stackoverflow.Main.main(Main.java:23)

      

+2


source







All Articles