Dynamically get the current line number

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)