这里Joiner
的初始化是否不正确?我有以下类,当我尝试使用 joiner
连接示例 paths
数组时,我收到一个 NullPointerException
。
public class CPath {
private static final Joiner joiner = Joiner.on("/");
private String[] elements;
@Override
public String toString() {
return joiner.join(elements);
}
}
// main method
final String[] paths = {"a/b/c", "d", "", null, "e/f/g", "h/i", null, ""};
final CPath c3 = new CPath(paths);
c3.toString(); //<<<< NPE
最佳答案
您必须使用 skipNulls()
或 useForNull(defaultValue)
,它位于其文档的顶部;
If neither skipNulls() nor useForNull(String) is specified, the joining methods will throw NullPointerException if any given element is null.
所以你必须像这样初始化joiner
;
Joiner joiner = Joiner.on("/").skipNulls();
或
Joiner joiner = Joiner.on("/").useForNull("");
关于java - Guava Joiner 对 null 元素抛出 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43476156/