如何在Guice中获取动态类型/动态构建的ParameterizedType的实例 [英] How to get instance for dynamic type/dynamically built ParameterizedType in Guice
本文介绍了如何在Guice中获取动态类型/动态构建的ParameterizedType的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑到注入器,我想知道如何检索某些参数化类型的特定实例(但我自己没有Type
).让我解释一下自己:
Given an injector, I am wondering how I can retrieve a specific instance of some parameterized type (but I don't have the Type
itself). Let me explain myself:
想象一下您已经进行了以下绑定:
Imagine that you have made the following bindings:
-
List<Apple>
绑定到ArrayList<Apple>
-
Set<Pears>
绑定到HashSet<Pear>
- 等...,用于
Fruit
的其他Collection
.
List<Apple>
bound toArrayList<Apple>
Set<Pears>
bound toHashSet<Pear>
- etc... for other
Collection
ofFruit
.
现在我有一个Fruit fruit
实例,我想检索适当的Collection
实例.我该如何实现?
Now I have a Fruit fruit
instance and I would like to retrieve the appropriate Collection
instance. How can I achieve this?
这是一个小的工作片段,其中用代码说明了我的所有解释:
Here is a small working snippet that illustrates with code all my explanations:
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())
}
}
推荐答案
好的,我最终找到了解决方法:
OK, I eventually found the solution:
private static <T extends Fruit> void addFruit(Injector injector, T fruit) {
Collection<T> collection = (Collection<T>) injector.getInstance(Key.get(Types.newParameterizedType(Collection.class,
fruit.getClass())));
collection.add(fruit);
}
关键是使用com.google.inject.util.Types
类的Types.newParameterizedType()
.
这篇关于如何在Guice中获取动态类型/动态构建的ParameterizedType的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文