MapUtils.getString
是 Apache Commons Collections 库中的一个方法,用于从 Map
中安全地获取字符串值。这个方法可以避免直接从 Map
中获取值时可能出现的 NullPointerException
,并且可以提供一个默认值。
方法签名
public static String getString(Map map, Object key)
public static String getString(Map map, Object key, String defaultValue)
参数说明
map
:要从中获取值的Map
对象。key
:要获取值的键。defaultValue
(可选):如果键不存在或值为null
时返回的默认值。
返回值
- 如果
map
中存在指定的key
,且对应的值不为null
,则返回该值的字符串表示。 - 如果
map
中不存在指定的key
,或对应的值为null
,则返回defaultValue
(如果提供了),否则返回null
。
示例代码
import org.apache.commons.collections4.MapUtils;
import java.util.HashMap;
import java.util.Map;
public class MapUtilsExample {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("name", "John");
map.put("age", 30);
// 使用 getString(Map, Object)
String name = MapUtils.getString(map, "name");
System.out.println(name); // 输出: John
// 使用 getString(Map, Object, String)
String address = MapUtils.getString(map, "address", "Unknown");
System.out.println(address); // 输出: Unknown
// 当键存在但值为 null 时
map.put("city", null);
String city = MapUtils.getString(map, "city", "Unknown City");
System.out.println(city); // 输出: Unknown City
}
}
注意事项
- 类型转换:
MapUtils.getString
方法会将值转换为字符串,因此即使值是其他类型(如整数),也会被转换为字符串。 - 依赖库:使用
MapUtils
需要引入 Apache Commons Collections 库。确保在项目的构建文件中添加相应的依赖。
例如,在 Maven 项目中,可以在 pom.xml
中添加以下依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>