简体   繁体   中英

How to add generated implementation to Dagger Dependency Graph?

I have an interface

public interface SomeInterface { 
  void test(); 
}

and an annotation processor which generates an implementation of SomeInterface called SomeInterfaceImpl .

To make this type available with Dagger dependency injection I would create the following:

@Component(modules = {ApplicationModule.class})
@Singleton
public interface ApplicationComponent {    
    SomeInterface getSomeInterface();       
}

and

@Module
public class ApplicationModule {

    @Provides
    @Singleton
    SomeInterface provideSomeInterface() {
        return new SomeInterfaceImpl();
    }
}

The problem is that I cannot use use SomeInterfaceImpl in my ApplicationModule because it is not yet available and will be generated by an annotation processor.

How can I extend my annotation processor such that I can use SomeInterface is available for Dagger dependency injection and that the generated implementation SomeInterfaceImpl will be resolved correctly?

Edit:

The example works, but I want to create the ApplicationModule with another annotation processor and let the processor integrate the ApplicationModule in the dagger graph somehow. @Component(modules={ApplicationModule.class}) Will not exist because I do not know in code that ApplicationModule will be generated. Is there a way to integrate a generated a @Module class into the Dagger Graph? Note that I do not want to guess that ABCModule will be generated and add it to the @Component. I want that this happens automatically somehow.

As long as the annotations are both in the same javac invocation, and as long as you eventually do generate your class within one of the processor rounds, Dagger should defer trying to use the symbol until a later round.

However, in your specific situation cited above, Dagger's processor won't even try to access SomeInterfaceImpl directly, because that's within the body of a @Provides method, and annotation processors cannot (through public APIs) access method body content. So Dagger shouldn't even care if SomeInterfaceImpl is generated in time or not - but the code Dagger generates may not compile (nor will the module itself) if you don't generate before the last round.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM