Lets imagine this situation: we have Class1 and Class2
public class Class1 {
private Class2 field;
public Class1() {}
public doStuff() {
this.field = new Class2();
}
}
public class Class2 {
public Class2() {} //get Class1 instance that has called this method
}
I want to know if it is possible to get Class1 instance in Class2 constructor somehow.
I’ve been thinking about viewing a stack trace but it looks like a bad way
>Solution :
Since your Class2 always seems to require a Class1 object, this might be a pretty good case for an inner class.
public class Class1 {
private Class2 field;
public doStuff() {
this.field = new Class2();
}
// Class2 is an inner class of Class1
public class Class2 {
public Class1 getCreatingClass1Instance() {
return Class1.this;
}
}
}
Whether this actually makes sense for you depends on the context. Your "get the Human that made the Sandwich is not one.