Guava Joiner在null元素上抛出NPE

时间:2017-04-18 15:21:28

标签: java guava

此处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

1 个答案:

答案 0 :(得分:2)

您必须使用skipNulls()useForNull(defaultValue),它位于文档的顶部;

  

如果既未指定skipNulls()也未指定useForNull(String),则如果任何给定元素为null,则连接方法将抛出NullPointerException。

所以你必须初始化joiner喜欢;

Joiner joiner = Joiner.on("/").skipNulls();

Joiner joiner = Joiner.on("/").useForNull("");

Documentation of Joiner from Guava