Java Isnull方法
时间:2020-02-23 14:35:02 来源:igfitidea点击:
在本教程中,我们将有关对象类的ISnull方法。
对象 isNull()方法用于检查对象是否为null。 java.util.Objects程序是在Java 7中引入的。
这是一个简单的例子 Object's isNull方法。
package org.igi.theitroad;
import java.util.Objects;
public class ObjectsIsNullMain {
public static void main(String[] args) {
String str1="theitroad";
String str2=null;
System.out.println("Is str1 null: "+Objects.isNull(str1));
System.out.println("Is str2 null: "+Objects.isNull(str2));
}
}
输出:
是str1 null:false是str2 null:true
让我们来看看源代码对象的isnull()方法。
/**
* Returns {@code true} if the provided reference is {@code null} otherwise
* returns {@code false}.
*
* @apiNote This method exists to be used as a
* {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
*
* @param obj a reference to be checked against {@code null}
* @return {@code true} if the provided reference is {@code null} otherwise
* {@code false}
*
* @see java.util.function.Predicate
* @since 1.8
*/
public static boolean isNull(Object obj) {
return obj == null;
}
如我们所见,它只需检查OBJ为null。
isnull over obj == null的优势
1.如果布尔变量是null的情况下,我们正在检查是否为null。
我们可以如下制作拼写错误。
Boolean boolVar=true;
if(boolVar = null) //typo
{
}
我们可以使用 isNull()避免这种拼写的方法。
Boolean boolVar=true;
if(Objects.isNull(boolVar)) //typo
{
}
2.对象的 isNull()方法可以与Java 8 Lambda表达式一起使用。
它更简洁,更容易写。
.stream().filter(Objects::isNull)
它比下面的式子更容易写:
.stream().filter(a -> a == null).

