Guice:如何为所有类型绑定泛型? [英] Guice: how do I bind generics for ALL types?

查看:87
本文介绍了Guice:如何为所有类型绑定泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的代码中经常重复以下模式:

Suppose I have the following pattern repeating often in my code:

class A<T> {
    @Inject
    public A(List<T> list) {
        // code
    }
}

我想将全部 List<T>绑定到ArrayList<T>. 我知道我可以使用TypeLiteral绑定一个显式的原始类型,例如List<String>,但是无论如何,对于所有类型都可以这样做吗?

I want to bind all List<T> to ArrayList<T>. I know I can use TypeLiterals to bind an explicit raw type, e.g., List<String>, but is there anyway to do this for all types?

基本上,此代码不会失败,因为我没有明确绑定List:

Basically, this code should not fail because I didn't bind List explicitly:

injector.getInstance(new Key<A<Integer>>(){});

推荐答案

在Guice中这是不可能的.在内部,Guice只不过是HashMap<Key, Provider<?>>,其中Key表示可选的绑定批注和单个完全限定的类型.要匹配类型的模式",将要求Key的行为更像谓词,这将需要非常不同的体系结构,并使绑定查找要慢得多.

This is not possible in Guice. Internally Guice is little more than a HashMap<Key, Provider<?>>, where a Key represents an optional binding annotation and a single fully-qualified type. To match a "pattern" of types would require a Key to behave more like a predicate, which would require a very different architecture and which would make binding lookup much slower.

此外,尽管您可能使用List作为一个简单的示例,但请记住,Guice绑定最好保留给可能在生产或测试中有所不同的等效实现.列表实现除了具有特定于算法的性能特征之外,它们处理null项的能力也各不相同,并且一旦为给定算法选择了理想的列表实现,就无需更改它了-特别是在应用程序范围的配置中.

Furthermore, though you may be using List for a simple example, remember that Guice bindings are better reserved for equivalent implementations that are likely to vary in production or tests. In addition to having very different algorithm-specific performance characteristics, List implementations vary in their ability to handle null items, and once you've picked an ideal list implementation for a given algorithm you're unlikely to need to change it—especially in an application-wide configuration.

如果您确实希望能够通过Guice样式的配置来更改通用实现,请创建一个非常小的工厂,例如ListFactory:

If you do want to be able to vary your generic implementations with Guice-style configuration, create a very small factory like ListFactory:

public class ListFactory {
  public <T> List<T> createFooBarList() { return new ArrayList<T>(); }
  public <T> List<T> createSomeOtherList() { return new LinkedList<T>(); }
}

这篇关于Guice:如何为所有类型绑定泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆