给定一个注入器,我想知道如何检索某个参数化类型的特定实例(但我没有它Type
本身)。让我解释一下自己:
假设您进行了以下绑定:
List<Apple>
势必ArrayList<Apple>
Set<Pears>
势必HashSet<Pear>
- 等等……对于其他
Collection
的Fruit
。
现在我有一个Fruit fruit
实例,我想检索适当的Collection
实例。我怎样才能做到这一点?
这是一个小的工作片段,用代码说明了我的所有解释:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
public class TestGuiceDynamicType {
public static interface Fruit {
}
public static class Apple implements Fruit {
}
public static class Pear implements Fruit {
}
public static class FruitModule extends AbstractModule {
@Override
protected void configure() {
bind(new TypeLiteral<Collection<Apple>>() {
}).to(new TypeLiteral<ArrayList<Apple>>() {
});
bind(new TypeLiteral<Collection<Pear>>() {
}).to(new TypeLiteral<HashSet<Pear>>() {
});
}
}
private <T extends Fruit> static void addFruit(Injector injector, T fruit) {
Collection<T> collection = ????? // What to do here to get the appropriate collection
collection.add(fruit);
}
public static void main(String[] args) {
Injector injector = Guice.createInjector(new FruitModule());
Collection<Apple> appleCollection = injector.getInstance(Key.get(new TypeLiteral<Collection<Apple>>() {
}));
appleCollection.add(new Apple());
addFruit(injector, new Pear())
}
}