File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Object says Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Object says "Who Watch "Object says "Who New topic

Object says "Who's asking?" before executing method

Tom Pepe'

Joined: Nov 02, 2002
Posts: 20
Is it possible to search though a path list, and find out what object called the method currently running.
Julia Reynolds
Ranch Hand

Joined: May 31, 2001
Posts: 123
One quick and dirty way to do this is have the method throw an Exception, and then wrap it in a try catch and print the stack trace. Below is a test class to demonstrate.
import java.lang.Exception;
public class Throw{
public static void main(String[] args){
}catch(Exception ex){

public static void doWork() throws Exception{
}catch(Exception ex){

throw new Exception();
}//end Throw
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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 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 ]

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Object says "Who's asking?" before executing method
It's not a secret anymore!