Let's say I have a class that instantiates and uses another class. From the second class, is it possible to gain access to the first one? For example:
public class A {
public B obj = new B();
public void something() {
b.somethingElse();
}
}
public class B {
public void somethingElse() {
A owner = getCallingObject();
//the object of class A that called b.somethingElse() is now stored in owner
}
public Object getCallingObject() {
// ?????
// returns the A that instantiated/owns this B
}
}
I know how to get the Class of that object using something like this:
private String getCallerClassName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
for (int i = 1; i < stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals(B.class.getName()) && ste.getClassName().indexOf("java.lang.Thread") != 0)
return ste.getClassName();
}
return null;
}
which I got from a different question: How to get the caller class in Java. Is there a way to get a pointer to the caller object?