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
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!

30.4k questions

32.5k answers

500 comments

108k users

Browse Categories

...