如何在Guice中获取动态类型/动态构建的ParameterizedType的实例

时间:2013-06-03 17:46:39

标签: java guice

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

想象一下,您已经进行了以下绑定:

  • List<Apple>绑定到ArrayList<Apple>
  • Set<Pears>绑定到HashSet<Pear>
  • etc ...用于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())
    }
}

1 个答案:

答案 0 :(得分: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()的{​​{1}}。