Dynamically get the current line number

前端 未结 5 1972
一整个雨季
一整个雨季 2020-12-14 00:58

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

5条回答
  •  [愿得一人]
    2020-12-14 01:09

    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.

提交回复
热议问题