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

2019-07-19 17:06发布

问题:

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



标签: java dagger-2