Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading