How to introduce things to objects 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 an object B 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 do the injection work if I created object B using reflection (and not injection via Guice)?

+4
source share
3 answers

MembersInjector<B> a MembersInjector<B> and use this to enter 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 in advance. If there are problems with B injection, you will know when you create the injector that the application normally starts. This is preferable to Injector.injectMembers() , because it will not work until it is called.

+8
source

You can call injector.injectMembers(myObject) , but I doubt it follows the best practices.

+2
source

Either / or: you can put it under the control of the DI engine or take it on yourself, but it's hard to have both.

The only way I can think of is to tell the DI engine about the factory method, which can use reflection to create an instance. But this is the only mechanism that comes to mind.

0
source

Source: https://habr.com/ru/post/1337676/


All Articles