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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With