Is it possible to get beans by class type in Dagger2 similarly to Spring does?

Viewed 226

Spring framework allows to get beans by class type in the following way:

ApplicationContext context;
Class<? extends Foo> fooClass;
Foo fooBean = context.getBean(fooClass);

Is there any way to achieve something similar to this with Dagger2?

1 Answers

As far as I know, only if you manually define a map multibinding over the class as a map key.

@Singleton
public class MyClass {
    @Inject
    public MyClass() {}
}

@Module
public abstract class MyModule {
    @Binds
    @IntoMap
    @ClassKey(MyClass.class)
    public abstract Object bindMyClass(MyClass impl);
}

And then

@Inject
Map<Class<?>, Provider<Object>> providers;

MyClass myClass = (MyClass)providers.get(MyClass.class).get();

It'd be possible to restrict the key to ? extends MyClass with custom keys.

@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface FooKey {
    Class<? extends Foo> value();
}
Related