Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get line number of method caller?

Is there any way to get the line number of the caller of a method in Java? I don't want to have to throw an exception. Do I have to work with stack traces? Is there any way to do this in a cheap way?

EDIT: To clarify, I don't want the line number of the caller's class. I want the exact line where the method was called.

like image 482
nulldev Avatar asked Jun 30 '15 01:06

nulldev


1 Answers

The answer that Aasmund provided works, but you're better using

Thread.getStackTrace() than Exception.getStackTrace(), because you're not actually interested in the exception.

In practical terms, it won't make much difference, but your code will reflect your intention more clearly.

int callersLineNumber = Thread.currentThread().getStackTrace()[1].getLineNumber();
like image 117
Tim Avatar answered Oct 06 '22 00:10

Tim