Inject but pass an existing reference?

46 views
Skip to first unread message

Robert Nicholson

unread,
Jul 14, 2017, 11:39:24 AM7/14/17
to google-guice
So I create an instance of a class using

injector.getInstance(Someclass.class);

this returns me an instance of Someclass

what I want is at the point of the injection for Someclass to have a reference to "this" ie. the instance where I'm performing
the injection.

I don't want Guice to create a new object as this object already exists.

public Class A {
public createSomeclass() {
SomeModule module = new Module
return injector.getInstance(Someclass.class)
}

}

So I want the instance of Someclass to have a reference of the instance of Class A where the inject is taking place.

So how do I do this without needing to write someClassInstance.setClassAReference(this)

Currently Guice is not responsible for instantiating the instance of class A.

Stephan Classen

unread,
Jul 14, 2017, 5:13:06 PM7/14/17
to google...@googlegroups.com
I don't think guice can do this. Maybe there is a hook you could use to take controle while the injection happens. Does someone else know more?

What you could do as an alternative is to use assisted injection and then manually pass this as an assisted parameter. The advantages over calling a setter are:
- this is already passed to the constructor.
- because it is part of the interface one cannot forget to pass it

Hope this helps.
Reply all
Reply to author
Forward
0 new messages