gpt4 book ai didi

java - 访问 map 中嵌套属性的简单方法

转载 作者:搜寻专家 更新时间:2023-11-01 03:36:20 24 4
gpt4 key购买 nike

我使用以下代码直接访问示例中嵌套映射结构中的任何属性。

import com.google.common.collect.ImmutableMap;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.core.env.MapPropertySource;

import java.util.Map;

public class MapPropertySourceLearningTest {

@Test
public void testFlattenedMap() {
Map map = ImmutableMap.of(
"meta", ImmutableMap.of(
"pagination", ImmutableMap.of(
"position", "1",
"itemsPerPage", "50",
"totalPages", "9",
"totalItems", "438"
)
)
);

MapPropertySource source = new MapPropertySource("map", new YamlProcessor() {
public Map<String, Object> flatten(Map<String, Object> source) {
return super.getFlattenedMap(source);
}
}.flatten(map));

Assert.assertEquals("1", source.getProperty("meta.pagination.position"));
Assert.assertEquals("9", source.getProperty("meta.pagination.totalPages"));
}


}

我不喜欢必须扩展 YamlProcessor 类。 ¿ 是否有更好的方法来实现同样的目标?

最佳答案

或者PropertyUtils.getProperty (返回一个对象)或 BeanUtils.getProperty (返回一个字符串)在 Apache Commons BeanUtils会适合你的需要。尽管它们会抛出一些难以处理的异常,因此您可能希望创建自己的包装器方法来处理您认为合适的异常。

Assert.assertEquals("1", PropertyUtils.getProperty(map, "meta.pagination.position"));
Assert.assertEquals("9", PropertyUtils.getProperty(map, "meta.pagination.totalPages"));
Assert.assertEquals("1", BeanUtils.getProperty(map, "meta.pagination.position"));
Assert.assertEquals("9", BeanUtils.getProperty(map, "meta.pagination.totalPages"));

关于java - 访问 map 中嵌套属性的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30501494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com