简体   繁体   中英

knowing the caller object or thread from static method

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()
    }
}

实际上,您可以打印堆栈跟踪以了解从哪个线程和对象调用它。

You can use

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

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

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.

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.

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());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM