如何在使用反射创建的对象上注入东西?

Cri*_*ian 4 java guice code-injection

一个简单的例子:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我使用反射创建B对象:

class A{
     A(){
         // blah blah blah 
         B b = constructor.newInstance();
         b.doSomething(); // sigh, this prints null!!!
     }
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:如果我使用反射创建B对象(而不是通过Guice注入),如何使注入工作?

Jes*_*son 8

注入MembersInjector<B>并使用它来注入以下字段和方法B:

class A {
    @Inject A(MembersInjector<B> bInjector) {
        ...
        B b = constructor.newInstance();
        bInjector.injectMembers(b);
        b.doSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法最好的部分是Guice可以提前准备B的绑定.如果注入B会出现问题,你会发现创建注入器的时间,通常是应用程序启动.这是首选,Injector.injectMembers()因为在调用它之前不会失败.