Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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 (4k points)
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...