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