简体   繁体   English

Dagger2如何基于Java类进行注入?

[英]Dagger2 How can I inject based on a java class?

I have an enum with a bunch of classes that are, currently, being created using the newInstance() method on the Class object. 我有一个带有一堆类的枚举,这些类当前正在使用Class对象上的newInstance()方法创建。 I would like to start using dependency injection here. 我想在这里开始使用依赖注入。

With the original dagger I could have said ObjectGraph#get(item.getClazz()) . 使用原始的匕首,我可以说是ObjectGraph#get(item.getClazz()) Is there a way to achieve something similar with Dagger2? 有没有办法用Dagger2达到类似的目的? (I'm really liking the dagger2 interface and would prefer not to have to go back to dagger1). (我真的很喜欢dagger2界面,不希望不必回到dagger1)。

Dagger 2 doesn't have any built-in mechanism for getting instances via Class objects. Dagger 2没有任何通过Class对象获取实例的内置机制。

Given your sample code, I would guess that your enum looks something like: 给定您的示例代码,我猜您的枚举看起来像:

enum Item {
  ONE(A.class),
  TWO(B.class);

  private final Class<?> clazz;
  private Item(Class<?> clazz) { this.clazz = clazz; }
  Class<?> getClazz() { return clazz; }
}

In order to get calling code that behaves similarly to the version you suggested with ObjectGraph , you need a @Component with methods for each of the types referenced by Item . 为了获得与ObjectGraph所建议的版本行为类似的调用代码,您需要一个@Component其中包含Item引用的每种类型的方法。

@Component
interface MyComponent {
  A getA();
  B getB();
}

Now, you can update Item to delegate to MyComponent instead and remove the need for the class literals altogether. 现在,您可以更新Item以委托给MyComponent,而完全不需要类文字。

enum Item {
  ONE {
    @Override A getObject(MyComponent component) {
      return component.getA();
    } 
  },
  TWO {
    @Override B getObject(MyComponent component) {
      return component.getB();
    }
  };

  abstract Object getObject(MyComponent component);
}

Now, rather than ObjectGraph#get(item.getClazz()) , you can just call item.getObject(myComponent) for the same effect. 现在,您可以只调用item.getObject(myComponent)以获得相同的效果,而不是ObjectGraph#get(item.getClazz())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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