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

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

java - Dynamically get the current line number

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...