在guava提倡的Using and avoiding null中,有关于此方法的相关描述:
Whenever you want a
null
value to be replaced with some default value instead, useMoreObjects.firstNonNull(T, T)
. As the method name suggests, if both of the inputs are null, it fails fast with aNullPointerException
. If you are using anOptional
, there are better alternatives -- e.g.first.or(second)
.
意思是当您希望用默认值替换空值时且为非Optional时,请使用MoreObject。
如果使用optional的话,可以使用optional的or()方法;
此方法要求传递两个参数。从命名上看仿佛描述了一个first参数不为空的处理,其实此方法类似于咱常常使用的三目运算。其源码如下:
/**
* Returns the first of two given parameters that is not {@code null}, if either is, or otherwise
* throws a {@link NullPointerException}.
*
* <p>To find the first non-null element in an iterable, use {@code
* Iterables.find(iterable, Predicates.notNull())}. For varargs, use {@code
* Iterables.find(Arrays.asList(a, b, c, ...), Predicates.notNull())}, static importing as
* necessary.
*
* <p><b>Note:</b> if {@code first} is represented as an {@link Optional}, this can be
* accomplished with {@link Optional#or(Object) first.or(second)}. That approach also allows for
* lazy evaluation of the fallback instance, using {@link Optional#or(Supplier)
* first.or(supplier)}.
*
* @return {@code first} if it is non-null; otherwise {@code second} if it is non-null
* @throws NullPointerException if both {@code first} and {@code second} are null
* @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}).
*/
public static <T> T firstNonNull(@Nullable T first, @Nullable T second) {
return first != null ? first : checkNotNull(second);
}
checkNotNull方法的源码如下:
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
以上可以看出:
1、其用法为如果两个参数都不为空,则返回第一个;
2、如果都为空,则抛出空指针异常
3、如果其中一个为空,返回不为空的那个
具体测试代码如下:
private static void testMoreObjectsFirstNonNull() {
List<String> testList1 = Lists.newArrayList("a", "b", "c");
List<String> testList2 = Lists.newArrayList("1", "2", "3");
List<String> testList3 = null;
//大致意思就是如果其中一个为null就返回另外一个,都为null则抛出空指针
//step1 test all not null
System.out.println("test all not null,return first object : "+JsonMoreUtils.toJson(MoreObjects.firstNonNull(testList1, testList2)));
//step2 test first is null
System.out.println("test first is null,return another : "+JsonMoreUtils.toJson(MoreObjects.firstNonNull(testList3, testList2)));
//step3 test second is null
System.out.println("test second is null,return another : "+JsonMoreUtils.toJson(MoreObjects.firstNonNull(testList1, testList3)));
//step4 test all is null
System.out.println("test all is null: "+JsonMoreUtils.toJson(MoreObjects.firstNonNull(testList3, testList3)));
}
输出结果:

网友评论