Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 in the stack trace like this:

at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:348)

Now is there a way to print or log like in the below code?

log.error("Error in: " + this.getClass.getName() + "at line #"+ this.getClass.getActualLine());

You may ask, why don't I simply print the line number? Well because the code may get deleted or added before the specific log.error() method call.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
189 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...