此处Joiner
的初始化是否不正确?我有以下类,当我尝试将示例paths
数组加入joiner
时,我得到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
答案 0 :(得分:2)
您必须使用skipNulls()
或useForNull(defaultValue)
,它位于文档的顶部;
如果既未指定skipNulls()也未指定useForNull(String),则如果任何给定元素为null,则连接方法将抛出NullPointerException。
所以你必须初始化joiner
喜欢;
Joiner joiner = Joiner.on("/").skipNulls();
或
Joiner joiner = Joiner.on("/").useForNull("");