Possible Duplicate:
Get current stack trace in Java
I need to find the caller of a method. Is it possible using stacktrace or reflection?
Cisco Certified Network Associate Exam,640-802 CCNA All Answers ~100/100. Daily update
Possible Duplicate:
Get current stack trace in Java
I need to find the caller of a method. Is it possible using stacktrace or reflection?
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
ReplyDeleteAccording to the Javadocs:
The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.
A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().
You will have to experiment to determine which index you want (probably stackTraceElements[1] or [2]).
Sounds like you're trying to avoid passing a reference to this into the method. Passing this is way better than finding the caller through the current stack trace. Refactoring to a more OO design is even better. You shouldn't need to know the caller. Pass a callback object if necessary.
ReplyDelete