Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject things on objects that were created using reflection?

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)?

like image 506
Cristian Avatar asked Dec 29 '22 02:12

Cristian


1 Answers

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.

like image 134
Jesse Wilson Avatar answered Mar 09 '23 06:03

Jesse Wilson