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.