Is the inject method a reserved name? how Dagger-2

2019-07-19 17:25发布

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?

标签: java dagger-2
1条回答
萌系小妹纸
2楼-- · 2019-07-19 17:54

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...

查看更多
登录 后发表回答