Is the inject method a reserved name? how Dagger-2 knows to implement its body?

血红的双手。 提交于 2020-01-04 10:42:30

问题


I've seen this snippet:

@Component(modules = {TestActivityModule.class})
public interface TestActivityComponent {
    void inject(TestActivity activity);
}

But the inject method is not implemented in user code (but auto-generated in Dagger-2 code).

So is the inject a reserved name? how Dagger-2 knows to implement this method?


回答1:


Ok, I got it: the name doesn't matter, it can be e.g. squeeze, as long as the provided type contains @Inject fields(s)/methods(s)/constructor(s), Dagger-2 will generate the method's body:

@Component(modules = {TypoModule.class})
public interface TypoComponent {
    void squeeze(Thingie t);
}

...and as long as there's a @Provides that returns the @Injected type:

@Module class TypoModule {
    @Provides InjectedType whateverNameYouDecide() {
        return new InjectedSubType();
        // InjectedSubType extends InjectedType, obviously...
    }
}

Of course, Thingie should have @Injected member or nothing will happen:

class Thingie {
    @Inject InjectedType thingieID;
}

That's the whole story...



来源:https://stackoverflow.com/questions/37157771/is-the-inject-method-a-reserved-name-how-dagger-2-knows-to-implement-its-body

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!