1.需要引入依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.2</version>
</dependency>
2.例子
Map<String, Object> nullMap = null;
Map<String, Object> map = new HashMap<>();
map.put("user", new User());
map.put("boolean", true);
Assert.assertTrue(MapUtils.getBoolean(map, "boolean"));
//转换失败,返回默认值false
Assert.assertFalse(MapUtils.getBoolean(map, "user",false));
//目标map为null,返回null
Assert.assertNull(MapUtils.getBoolean(nullMap, "boolean"));
//目标map为null,返回默认值false
Assert.assertFalse(MapUtils.getBoolean(nullMap, "boolean", false));
Assert.assertTrue(MapUtils.getBooleanValue(map, "boolean"));
//转换失败,返回默认值false
Assert.assertFalse(MapUtils.getBooleanValue(map, "user",false));
//目标map为null,返回false
Assert.assertFalse(MapUtils.getBooleanValue(nullMap, "boolean"));
//目标map为null,返回默认值false
Assert.assertFalse(MapUtils.getBooleanValue(nullMap, "boolean", false));
map.put("integer", 5);
Assert.assertEquals(Integer.valueOf(5), MapUtils.getInteger(map, "integer"));
//转换失败,返回默认值5
Assert.assertEquals(Integer.valueOf(5), MapUtils.getInteger(map, "integer",5));
//目标map为null,返回null
Assert.assertEquals(null, MapUtils.getInteger(nullMap, "integer"));
//目标map为null,返回默认值5
Assert.assertEquals(Integer.valueOf(5), MapUtils.getInteger(nullMap, "integer", 5));
Assert.assertEquals(5, MapUtils.getIntValue(map, "integer"));
//转换失败,返回默认值5
Assert.assertEquals(5, MapUtils.getIntValue(map, "user",5));
//目标map为null,返回0
Assert.assertEquals(0, MapUtils.getIntValue(nullMap, "integer"));
//目标map为null,返回默认值5
Assert.assertEquals(5, MapUtils.getIntValue(nullMap, "integer", 5));
参考:https://blog.csdn.net/u012894692/article/details/82557843