In my previous article "Using HashMap in Custom Annotations", I explained how to use HashMap in annotations using enumeration constants.
Nested annotations can also be used to map key-value pairs.
List of types supported in annotations
Requires two custom annotations. The first annotation (such as MapItem) contains a key-value pair, and the second annotation (such as MapItems) contains a list of MapItem annotations.
The annotation @MapItem represents a single key-value pair.
<code class="language-java">@Target(ElementType.FIELD) public @interface MapItem { String key(); String value(); }</code>
The annotation @MapItems defines a MapItem list.
<code class="language-java">@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MapItems { MapItem[] items(); }</code>
The @MapItem annotation list is set in the @MapItems annotation.
<code class="language-java">class ExampleDto { @MapItems(items = { @MapItem(key = "1", value = "MALE"), @MapItem(key = "2", value = "FEMALE"), @MapItem(key = "6", value = "DIVERS") }) public String salutation; }</code>
MapItemsTest tests MapItems annotations. The test is performed on the salutation field.
To demonstrate how to use a @MapItem list, I create a HashMap from the @MapItem and compare it to the expected HashMap.
<code class="language-java">class MapItemsTest { @Test void testMapItems() throws NoSuchFieldException { Field field = ExampleDto.class.getDeclaredField("salutation"); field.setAccessible(true); MapItems annotation = field.getAnnotation(MapItems.class); Map<String, String> mappingItems = Arrays .stream(annotation.items()) .collect( Collectors.toMap( MapItem::key, MapItem::value ) ); assertEquals( new HashMap<>() {{ put("1", "MALE"); put("2", "FEMALE"); put("6", "DIVERS"); }}, mappingItems ); } }</code>
This is a neat solution and easy to implement.
For example, if key-value pairs are to be used in a validator, they must be obtained indirectly.
https://www.php.cn/link/164710e8521a5b39302f816392f05bc2
The above is the detailed content of Using nested annotations for key-value pairs in a custom annotation. For more information, please follow other related articles on the PHP Chinese website!