Several points here:
(1) No need to throw and catch an exception here - just create a Throwable and print (or analyze) its stack trace (see examples in (2) and (3)).
(2) If you're using a JDK older that 1.4, see
this article.
(3) If you're using JDK 1.4, analyzing a stack trace is much nicer. Here's a sample:
You can modify this to only look at part of the stack trace. I suspect you'll probably be most interested in the name of the class that had the method that called the method that has the StackTraceAnalyzer.show() method call. This would be element 2.
(4) Unfortunately, the stack trace can not tell you which
object was involved in a call - it only gives you the
class name (along with method and line number). If you need to know the identity of the calling object, you'll need another strategy. If you're just trying to identify the calling object of the current method, that's easy - the "this" keyword gives you a reference to that object. However to find objects associated with other methods from other classes (or static methods of the same class) in the call stack, it's much harder. The only way I can think of is, if you really need this information for a particular method, change its parameter list to include a reference to the associated calling object. This is a pain in the butt, and will only work for those methods you modify - it's not a general solution. Moreover it makes the API confusing, as you have to make clear to other programmers
what this extra object is which they're supposed to include. And if they include the wrong one, or null, or they lie - nothing you can do about it.
[ December 11, 2002: Message edited by: Jim Yingst ]