A simple example:
class C{}
class B{
@Inject C c;
void doSomething(){
System.out.println(c);
}
}
class A{
@Inject A(B b){
b.doSomething();//this works fine and prints the c object
}
}
Now, if I create the B object using reflection:
class A{
A(){
// blah blah blah
B b = constructor.newInstance();
b.doSomething(); // sigh, this prints null!!!
}
}
So, my question is: how can I make the injection work if I have created the B object using reflection (rather than injection via Guice)?
Inject a MembersInjector<B>
and use that to inject the fields and methods of B
:
class A {
@Inject A(MembersInjector<B> bInjector) {
...
B b = constructor.newInstance();
bInjector.injectMembers(b);
b.doSomething();
}
}
The best part of this approach is that Guice can prepare the bindings for B ahead of time. If there will be problems injecting B, you'll find out when you create the injector, which is usually application startup. This is preferred over Injector.injectMembers()
because that won't fail until it is invoked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With