nulldev
nulldev

Reputation: 615

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.

Upvotes: 12

Views: 6971

Answers (2)

Tim
Tim

Reputation: 6509

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();

Upvotes: 23

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37940

You don't need to actually throw the exception; it is sufficient to create one:

int callersLineNumber = new Exception().getStackTrace()[1].getLineNumber();

Note that this requires neither try/catch nor a throws declaration.

Upvotes: 2

Related Questions