Cogman
Cogman

Reputation: 2150

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

Upvotes: 1

Views: 409

Answers (1)

gk5885
gk5885

Reputation: 3762

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.

Upvotes: 2

Related Questions