问题
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>
bound toArrayList<Apple>
Set<Pears>
bound toHashSet<Pear>
- etc... for other
Collection
ofFruit
.
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())
}
}
回答1:
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);
}
The key is to use Types.newParameterizedType()
of the class com.google.inject.util.Types
.
来源:https://stackoverflow.com/questions/16902707/how-to-get-instance-for-dynamic-type-dynamically-built-parameterizedtype-in-guic