Annotation Type MapKey
-
@Documented @Target(ANNOTATION_TYPE) @Retention(RUNTIME) public @interface MapKey
Identifies annotation types that are used to associate keys with values returned by provider methods in order to compose a map.Every provider method annotated with
@Provides
and@IntoMap
must also have an annotation that identifies the key for that map entry. That annotation's type must be annotated with@MapKey
.Typically, the key annotation has a single member, whose value is used as the map key.
For example, to add an entry to a
Map<SomeEnum, Integer>
with keySomeEnum.FOO
, you could use an annotation called@SomeEnumKey
:@MapKey @interface SomeEnumKey { SomeEnum value(); } @Module class SomeModule { @Provides @IntoMap @SomeEnumKey(SomeEnum.FOO) Integer provideFooValue() { return 2; } } class SomeInjectedType { @Inject SomeInjectedType(Map<SomeEnum, Integer> map) { assert map.get(SomeEnum.FOO) == 2; } }
If
unwrapValue
is true, the annotation's single member can be any type except an array.See
dagger.multibindings
for standard unwrapped map key annotations for keys that are boxed primitives, strings, or classes.Annotations as keys
If
unwrapValue()
is false, then the annotation itself is used as the map key. For example, to add an entry to aMap<MyMapKey, Integer>
map:@MapKey(unwrapValue = false) @interface MyMapKey { String someString(); MyEnum someEnum(); } @Module class SomeModule { @Provides @IntoMap @MyMapKey(someString = "foo", someEnum = BAR) Integer provideFooBarValue() { return 2; } } class SomeInjectedType { @Inject SomeInjectedType(Map<MyMapKey, Integer> map) { assert map.get(new MyMapKeyImpl("foo", MyEnum.BAR)) == 2; } }
(Note that there must be a class
MyMapKeyImpl
that implementsMyMapKey
in order to callMap.get(Object)
on the provided map.)- See Also:
- Map multibinding
-
-
Optional Element Summary
Optional Elements Modifier and Type Optional Element Description boolean
unwrapValue
True to use the value of the single member of the annotated annotation as the map key; false to use the annotation instance as the map key.
-