How to get a dagger instance from a type known only at runtime

I am processing an annotation with a type parameter. This type parameter is used to instantiate a new object.

With Google Guice, I would enter “Injector” myself and use it to find the right instance. However, I am a little new to Dagger, and I do not see any solutions described on the net. I know that ObjectGraph can give me an instance. Can I / I be allowed to enter ObjectGraph itself? How should I do it?

+3
source share
1 answer

I managed to do it like this. Not sure if this is good ...

Bar:

public class Bar {

    private ObjectGraph objectGraph;

    @Inject
    Bar(ObjectGraph objectGraph){

        this.objectGraph = objectGraph;
    }

    public ObjectGraph getObjectGraph() {
        return objectGraph;
    }
}

BarModule:

@Module(
        injects = Bar.class,
        complete = false
)
public class BarModule {
}

FooModule:

@Module(
        includes = BarModule.class,
        injects = ObjectGraph.class,
        complete = true,
        library = true
)
public class FooModule {

    private ObjectGraph objectGraph;

    public void setObjectGraph(ObjectGraph objectGraph){

        this.objectGraph = objectGraph;
    }

    @Provides @Singleton ObjectGraph providesObjectGraph(){
        return null;
    }
}

EntryPoint:

public class EntryPoint {

    public static void main(String[] args){
        FooModule fooModule = new FooModule();
        ObjectGraph objectGraph = ObjectGraph.create(new BarModule(), fooModule);
        fooModule.setObjectGraph(objectGraph);

        System.out.println(objectGraph);

        Bar bar = objectGraph.get(Bar.class);
        ObjectGraph objectGraph1 = bar.getObjectGraph();

        System.out.println(objectGraph);
    }
}
+2
source

All Articles