Guice: how do I bind generics for ALL types?

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

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

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

Basically, this code should not fail because I did not explicitly bind List:

 injector.getInstance(new Key<A<Integer>>(){}); 
+6
source share
1 answer

This is not possible in Guice. Internal Guice is a bit more than a HashMap<Key, Provider<?>> , where Key represents an optional binding annotation and one fully qualified type. To match the β€œpattern” of types, the Key will need to be more like a predicate, which would require a completely different architecture and which would make binding the search much slower.

Also, although you can use List for a simple example, remember that Guice bindings are better reserved for equivalent implementations, which may vary during production or testing. In addition to the very different performance characteristics specific to a particular algorithm, List implementations differ in their ability to process null elements, and once you have chosen the ideal list implementation for this algorithm, you are unlikely to need to change it, especially in the application configuration.

If you want to change your general implementations using a 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>(); } } 
+3
source

Source: https://habr.com/ru/post/985268/


All Articles