0

I have a static method of a class and which is being called from another non static method from an object or thread.
Is there a way to know that from which thread or object it was called?
I think it's not possible and I need it for nothing, but just want to confirm it.

I mean something like this

class CallerID
{
    public static void main(String ...s)
    {
        CallerID ob=new CallerID();
        ob.caller();
    }
    void caller()
    {
        showCaller();
        System.out.println("In this method, ob = "+this);
    }
    static void showCaller()
    {
        //code to get caller object ob like it is printed in method caller()
    }
}
5
  • 1
    So, do you want the calling object, or the current thread? Those are completely different things. Thread.currentThread() returns the current thread.
    – JB Nizet
    Jul 14, 2013 at 14:25
  • "Is there a way to know that from which thread or object it was called?" Your question makes no sense.
    – m0skit0
    Jul 14, 2013 at 14:27
  • It's not possible, but your actual problem can probably be solved in a better way. Tell us what you really want to achieve.
    – JB Nizet
    Jul 14, 2013 at 14:44
  • @Nizet as I said "I need it for nothing". Just trying something. Thanks anyway. Jul 14, 2013 at 14:46
  • I could imagine a complex setup that used AOP to create some kind of context database that allowed you to lookup the calling object if you wanted - but I can't think of why you would want to.
    – selig
    Jul 14, 2013 at 21:02

5 Answers 5

1

You can't get the object calling. You can get the calling object, thread, and method, but if you want a reference you'll have to pass this as a parameter.

1

Actually you can print a stack trace to know from which thread and object it is called.

1
  • not the object, just the method and class, and you don't need to print it. Jul 14, 2013 at 14:27
1

You can use

StackTraceElement[] el = Thread.currentThread().getStackTrace();

to look at the backtrace and from this you can find the caller there.

0
1

The thread could be found with Thread.currentThread(). The calling object although cannot be found. The calling method could be found by parsing a stack trace, although that might be quite slow.

1

You can look in thread's most recent stack trace, usually its the fourth entry, or you can iterate to check:

 StackTraceElement[] trace = Thread.currentThread().getStackTrace();
 if(trace.length > 3){
   System.out.println("Called from method " + trace[3].getMethodName() + " of class " + trace[3].getClassName());
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.