0 votes
1 view
in Java by (3.9k points)

I need to find the caller of a method. Is it possible using stacktrace or reflection?

1 Answer

0 votes
by (46.1k points)

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()

From the Javadocs:

The last element of the array represents the bottom of the stack, which is the least latest method invocation in the sequence.

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

You will have to test to decide which index you require (apparently stackTraceElements[1] or [2]).

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4.1k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Aditya98 (1.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...