在 Guice 中注入通用工厂
2022-09-04 23:24:42
下面的代码是生成给定的 .工厂不在乎是什么:对于任何类型,它都可以从.Bar<T>
Foo<T>
T
T
Bar<T>
Foo<T>
import com.google.inject.*;
import com.google.inject.assistedinject.*;
class Foo<T> {
public void flip(T x) { System.out.println("flip: " + x); }
}
interface Bar<T> {
void flipflop(T x);
}
class BarImpl<T> implements Bar<T> {
Foo<T> foo;
@Inject
BarImpl(Foo<T> foo) { this.foo = foo; }
public void flipflop(T x) { foo.flip(x); System.out.println("flop: " + x); }
}
interface BarFactory {
<T> Bar<T> create(Foo<T> f);
}
class Module extends AbstractModule {
public void configure() {
bind(BarFactory.class)
.toProvider(
FactoryProvider.newFactory( BarFactory.class, BarImpl.class )
);
}
}
public class GenericInject {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new Module());
Foo<Integer> foo = new Foo<Integer>();
Bar<Integer> bar = injector.getInstance(BarFactory.class).create(foo);
bar.flipflop(0);
}
}
当我运行代码时,我从 Guice 收到以下错误:
1) No implementation for BarFactory was bound.
at Module.configure(GenericInject.java:38)
2) Bar<T> cannot be used as a key; It is not fully specified.
我在 Guice 文档中找到的泛型的唯一参考是使用 .但是我没有文字类型,我有一个与工厂完全无关的通用占位符。有什么提示吗?TypeLiteral