[英]Guice generic type injection
假設我有一個通用類,如下所示:
public class Base<T extends Stoppable> {
protected final Injector injector;
protected T stoppable;
public Base(Module... module) {
injector = Guice.createInjector(module);
Key<T> key = Key.get(new TypeLiteral<T>() {}); <-- T cannot be used as a key; It is not fully specified.
stoppable = injector.getInstance(key);
}
}
Stoppable
類型的實例使用Multibinder
綁定:
Multibinder<Stoppable> taskBinder =
Multibinder.newSetBinder(binder, Stoppable.class);
taskBinder.addBinding().to(MyClass.class);
有可能實現這一目標嗎?
不,不可能以您嘗試的方式實現這一目標。
但是您可以將Class
/ Type
對象傳遞給Base
的構造函數並使用它來創建所需的類型文字,例如(我使用Set
作為鍵,因為您提到了 multibinder):
public class Base<T extends Stoppable> {
protected final Injector injector;
protected T stoppable;
public Base(Class<T> type, Module... module) {
injector = Guice.createInjector(module);
var key = Key.get(com.google.inject.util.Types.setOf(type));
stoppable = injector.getInstance(key);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.