java – 在Map中访问嵌套属性的简便方法

weixin_38121257 2019-09-12 12:31:03
我使用以下代码直接访问嵌套映射结构中的任何属性,如示例中所示. 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类. ¿有没有更好的方法来实现同样的目标?
...全文
82 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38121708 2019-09-12
  • 打赏
  • 举报
回复
在Apache Commons BeanUtils中,PropertyUtils.getProperty(返回一个对象)或BeanUtils.getProperty(返回一个字符串)将满足您的需要.但是它们会抛出一些笨拙的异常,所以你可能想制作自己的包装方法来处理你认为合适的异常. 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"));

433

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧