0

I want to recover in Java the instance of the caller. Here is my code

class A {
    void methodA() {
        B b = new B();
        A a = b.methodB(); //needs to be the same instance ie "this"
    }
}

class B {
    A methodB() {
        //Here the code (with reflection) I need
        A a = getPreviousInstanceCaller();
        return A
    }
}

Does it exist in Java a way to do that ? Maybe with reflection ?

federem
  • 299
  • 1
  • 6
  • 17
  • What if the method was called from a `static` method? Look into the `StackTraceElement` class. You can find the class it was called from, but there wasn't necessarily an instance involved. – Sotirios Delimanolis Feb 08 '14 at 17:52
  • You can examine the stacktrace and get the element in the first 'hop'. As far as I know there is no other solution because a method call isn't something that's retained (except for the stacktrace). – Jeroen Vannevel Feb 08 '14 at 17:52

1 Answers1

2

You don't need reflection for this. You need one of these methods.

http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getStackTrace%28%29

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace%28%29

Note that the ordering of the stack trace elements (0, 1, 2, etc.)
may vary in different versions of the JDK. Meaning in some versions
element 0 may be the top-most element, while in others it may be the
bottom-most one. This is an important thing to have in mind.

See here for more details.

Getting the name of the current executing method

Community
  • 1
  • 1
peter.petrov
  • 38,363
  • 16
  • 94
  • 159