谁能解释一下这是什么?
public final String join(@Nullable Object first, @Nullable Object second,Object... rest) {
return this.join((Iterable)iterable(first, second, rest));
}
private static Iterable<Object> iterable(final Object first, final Object second, final Object[] rest) {
Preconditions.checkNotNull(rest);
return new AbstractList() {
public int size() {
return rest.length + 2;
}
public Object get(int index) {
switch(index) {
case 0:
return first;
case 1:
return second;
default:
return rest[index - 2];
}
}
};
}
为什么 join 方法不是这样的 - join(Object...args) ??? 实际上,如果我有一些例子:
String firstName = "John";
String lastName = "Doe";
public String getFullName(){
return Joiner.on(" ").skipNulls().join(first, lastName, null);
}
发生 NullPointerException !!!看起来很奇怪。 但如果我调用:
String firstName = "John";
String lastName = "Doe";
String parentName = null;
public String getFullName(){
return Joiner.on(" ").skipNulls().join(first, lastName, parentName);
}
输出:John Doe。
最佳答案
Why is the signature not
join(Object... args)
仅仅是因为 Guava 团队希望您确保您确实加入对象。为此,您至少需要 2 个参数。因此,前两个参数不会在运行时检查并出现异常,而是在编译时显式强制您使用多个对象。
所以这是一个强制你正确书写的设计。副作用是,实际上,您无法添加 null
作为第三个参数而不引发异常。如果您想显式使用可变参数并使用 null
,只需编写以下内容:
Joiner joiner = ...
joiner.join(Arrays.asList(firstName, lastName, null));
关于java - Guava Join 第三个参数 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28428788/