简体   繁体   中英

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. I would like to start using dependency injection here.

With the original dagger I could have said ObjectGraph#get(item.getClazz()) . Is there a way to achieve something similar with Dagger2? (I'm really liking the dagger2 interface and would prefer not to have to go back to dagger1).

Dagger 2 doesn't have any built-in mechanism for getting instances via Class objects.

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 .

@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.

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.

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