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

最佳答案

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


  如果未指定skipNulls()和useForNull(String),则任何给定元素为null时,联接方法都将引发NullPointerException。


因此,您必须像这样初始化joiner

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


要么

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


Documentation of Joiner from Guava

07-25 21:38