如何从仅在运行时知道的类型获取dagger实例

时间:2014-02-17 08:38:04

标签: java dependency-injection guice dagger

我正在处理具有类型参数的注释。此类型参数用于实例化新对象。

使用Google Guice,我会注入'Injector'本身并使用它来查找正确的实例。 但是我对Dagger有点新意,我没有看到网上描述的任何解决方案。我知道ObjectGraph可以给我一个实例。我/我是否可以注入ObjectGraph本身?我该怎么做?

1 个答案:

答案 0 :(得分:2)

我设法这样做了。不确定它是不是很好......

栏:

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);
    }
}