3

给定一个注入器,我想知道如何检索某个参数化类型的特定实例(但我没有它Type本身)。让我解释一下自己:

假设您进行了以下绑定:

  • List<Apple>势必ArrayList<Apple>
  • Set<Pears>势必HashSet<Pear>
  • 等等……对于其他CollectionFruit

现在我有一个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())
    }
}
4

1 回答 1

5

好的,我最终找到了解决方案:

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);
}

关键是使用Types.newParameterizedType()com.google.inject.util.Types

于 2013-06-03T18:20:23.340 回答