0
votes

I'm very new to Dagger 2 and I'm trying to get this basic example working with some minor modifications.

This is what I have so far:

Component class

@Component(modules = {MyModule.class})
public interface MyComponent {
void inject(Object object);
} 

Module class

@Module
public class MyModule {

@Provides
@Singleton
public Retrofit getRetrofit(){
  return new Retrofit();
}
}

Static Injector

public class MyStaticInjector {

private static MyComponent di;

public static void inject(Object object){
    if(di == null){
        di = DaggerMyComponent.builder().build();
    }
    di.inject(object);
}
}

The problem is that whenever I do

MyStaticInjector.inject(this);

the annotated fields are still null. I suspect the problem is with the type Object in the interface method. In the example, there's an Activity instead. But I need to use DI in classes that are not activities.

Can anyone help me? Thank you.

1
Object has no @Inject annotated fields. Thus the injection works just fine; it has nothing to inject. You will have to use your actual classes instead of Object, so that the code can be generated and fields can be injected.David Medenjak
I see... then is there any way to make a generic injector method? Or do I have overload the method inject in the interface for each of the injection class?Aurasphere
Dagger generates source code at compile time. If it does not know about the class, it cannot create code for it. You should read some more tutorials and try to learn more about dagger. Especially have a look at constructor injection.David Medenjak
Thank you, that was it. I'm used to DI at runtime with Spring or JSF so this is new to me. I'll take a look at more tutorials for sure. If you write an actual answer, I'll accept it. Thank you again.Aurasphere

1 Answers

5
votes

Object has no @Inject annotated fields. Thus the injection works just fine—it just has nothing to inject.
You will have to use your actual classes with inject(MyClass) instead of Object, so that the code can be generated and fields can be injected.

Dagger generates source code at compile time. If it does not know about the actual class, it cannot create code for it.