How to get instance for dynamic type/dynamically built ParameterizedType in Guice

我与影子孤独终老i 提交于 2019-12-10 18:55:36

问题


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 to ArrayList<Apple>
  • Set<Pears> bound to HashSet<Pear>
  • etc... for other Collection of Fruit.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!