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