ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-08-31 22:11:18  阅读:98  来源: 互联网

标签:java guice


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

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

>列表< Apple>绑定到ArrayList< Apple>
>设置<梨>绑定到HashSet< Pear>
>等…用于其他水果收集.

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

解决方法:

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

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().

标签:java,guice
来源: https://codeday.me/bug/20190831/1778859.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有