Is there a way in Java to dynamically get the current line number through reflection or some awesome API? Just like when exceptions occur, the line number gets printed out i
You can create a Throwable and use its StackTraceElements:
System.err.println(new Throwable().getStackTrace()[0].getLineNumber());
As @Joachim said, you can also use Thread.getStackTrace(), e.g. like
System.err.println(Thread.currentThread().getStackTrace()[1].getLineNumber());
Be aware that the second approach returns a somewhat different array - you need to use the array element with index 1 to get the current line number, since it includes the call to getStackTrace()
itself as the first element.
Also note the comments about Logging and performance from @Joachim's answer.