tags:

views:

152

answers:

5
A: 

this is always a reference to the current instance of the object. So any usage of this in foo() will return an instance of Class A.

matt b
I had a problem understanding the question, but I think he means to ask whether he could somehow get the reference to A (which he would get had he used "this")) while in bar.
Uri
A: 

I think that Java methods are generally not allowed to directly access the call stack.

From a security standpoint, you wouldn't want an API function potentially accessing the data of the caller.

Uri
+1  A: 

No, you can't. In all the languages that use a stack that I know of, the contents of other stack frames are hidden from you. There are a few things you can do to get it, beyond the obvious passing it as a parameter. One of the aspect oriented frameworks might get you something. Also, you can get a bit of debugging info from Thread.getStackTrace().

sblundy
In Smallalk, thisContext gives you a handle to the stack. You can manipulate the stack in any way you want. This is eg used in Seaside (the webapp framework) to implement continuations and thus implement the whole flow of many webpages or even the entire website in one method!
Adrian
+1  A: 

As other people have said, you will want your lower method to be passed the higher method's class instance and get it that way.

e.g:

Class A { 
    foo() {
        new b().bar(this);
    }
}

Class B {
    bar(A aInstance) {
        ...
    }
}
SCdF
+1  A: 

You have three choices. You can pass the calling object into the bar method:

Class A { 
    foo() {
        new B().bar(this);
    }
}

Class B {
    bar(A caller) {
        ...
    }
}

Or you can make class B an inner class of class A:

Class A { 
    foo() {
        new B().bar();
    }

    Class B {
        bar() {
            A caller=A.this;
            ...
        }
     }
}

If all you need is the Class rather than the object instance, you have a third choice. By using Thread.currentThread().getStackTrace(), you can get the qualified name of a class at an arbitrary point in the stack, and use reflection to obtain the class instance. But that is so horrible, you should either fix your design, or (if you are writing your own debugger or something similar) try a simpler project until you know enough about java to figure this kind of thing out for yourself...

Bill Michell