T
- The type of the list element.public class ListBinder<T> extends Object
ListBinder
is much like Multibinder
, except it provides a guaranteed iteration order, and binds a
List
instead of a Set
. For example:
ListBinder<String> listBinder = ListBinder.build(binder(), String.class) .withDefaultPriority(); listBinder.addBinding().toInstance("a"); listBinder.addBinding().toInstance("b");
This will create a binding for a List<String>
, which contains "a"
followed by "b"
. It also
creates a binding for List<Provider<String>>
— this may be useful in more advanced cases to allow list
elements to be lazily loaded.
To add an annotation to the list binding, simply write this:
ListBinder<String> listBinder = ListBinder.build(binder(), String.class) .annotatedWith(Names.named("name")) .withDefaultPriority();
and the created binding will be @Named("name") List<String>
instead.
For large lists, it may be helpful to split up their specification across different modules. This is accomplished by
specifying priorities for the ListBinder
s when they are created. For example:
// In some module ListBinder<String> listBinder1 = ListBinder.build(binder(), String.class) .withPriority(0); listBinder1.addBinding().toInstance("a"); listBinder1.addBinding().toInstance("b"); // ... some other module ListBinder<String> listBinder2 = ListBinder.build(binder(), String.class) .withPriority(1); listBinder2.addBinding().toInstance("c"); listBinder2.addBinding().toInstance("d");
The generated list will contain "a"
, "b"
, "c"
, "d"
, in order. This happens because
the first ListBinder
had a smaller priority, so its entries come first. For more information about the
priority system, see Priority
.
Modifier and Type | Method and Description |
---|---|
LinkedBindingBuilder<T> |
addBinding()
Add an entry to the list.
|
static <T> AnnotatedListBinderBuilder<T> |
build(Binder binder,
Class<T> type)
Start building a
ListBinder . |
static <T> AnnotatedListBinderBuilder<T> |
build(Binder binder,
TypeLiteral<T> type)
Start building a
ListBinder . |
String |
toString() |
public static <T> AnnotatedListBinderBuilder<T> build(Binder binder, Class<T> type)
ListBinder
.T
- The type of the list element.binder
- The current binder, usually AbstractModule.binder()
.type
- The type of the list element.public static <T> AnnotatedListBinderBuilder<T> build(Binder binder, TypeLiteral<T> type)
ListBinder
.T
- The type of the list element.binder
- The current binder, usually AbstractModule.binder()
.type
- The type of the list element.public LinkedBindingBuilder<T> addBinding()
The entry will be added in order for this ListBinder
instance. Between different ListBinder
s, the
order is determined by the ListBinder
's Priority
.
Copyright © 2014. All rights reserved.