File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Reflection; Method.invoke() and obtaining the stack trace Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reflection; Method.invoke() and obtaining the stack trace" Watch "Reflection; Method.invoke() and obtaining the stack trace" New topic

Reflection; Method.invoke() and obtaining the stack trace

Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Given an instance of java.lang.reflect.Method, I'd like to invoke it (by calling invoke()) and during execution of that method I'd like to obtain the stack trace (instance of StackTraceElement that corresponds to the method call). I can see no other way than to have the method itself obtain that information, which is not an option (I'd rather abolish the requirement). One hacky alternative is to call invoke from a low priority thread and then immediately obtain stack trace information of that thread from the 'main' thread with a higher priority and assume that the scheduler will always execute such that obtaining the stack trace occurs always before the call to method.invoke is complete. Can anyone see any reasonable alternatives?

Tony Morris
Java Q&A (FAQ, Trivia)
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Possibly you might be able to use JDI or JVMTI to set a breakpoint within the method before calling it. Then when you get the BreakpointEvent, call thread().frames() to get a list of StackFrames. I don't offhand see a way to get a StackTraceElement, but hopefully the StackFrame list has all the info you might need. More importantly, I don't know how easy it is to set a Breakpoint inside an arbitrary Method (if it's possible at all); I've never done it myself. But I'd be interested in hearing whether it can work or not, if you try it. Good luck.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Reflection; Method.invoke() and obtaining the stack trace
It's not a secret anymore!