Home > OS >  Is it possible to get instance of a class 2 where constructor of class 1 was called?
Is it possible to get instance of a class 2 where constructor of class 1 was called?

Time:06-29

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

CodePudding user response:

If you really need the instance of Class1, and not just the class name, then the only way would be something like this:

In Class1:

public doStuff() {
    this.field = new Class2(this);
}

In Class2:

public Class2(Class1 instance) {
    // do whatever you need with the Class1 instance)
}

CodePudding user response:

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.

  • Related