Optional对象是Java8新加入的一个容器,这个容器只存1个或0个元素,它用于防止出现NullpointException,它提供如下方法:
- isPresent()
判断容器中是否有值。(使用频率最高)
- ifPresent(Consume lambda)
容器若不为空则执行括号中的Lambda表达式。
- T get()
获取容器中的元素,若容器为空则抛出NoSuchElement异常。
- T orElse(T other)
获取容器中的元素,若容器为空则返回括号中的默认值。
Java判断各种情况下是否为空/不为空工具类
package util;
import java.util.Optional;
/**
* 判是否为空/不为空工具类
* @author fal
* @version v1.0
*/
public final class NullUtil {
private static final String NULL_STRING = "null";
private static final int NULL_STRING_LENGTH = NULL_STRING.length();
public NullUtil(){}
/**
* 判断参数是否不为null
* @param object 判断参数
* @return 如果object为空值(null)、空串("")或"null" 返回false,否则返回true
*/
public static boolean isNotNull(Object object){
if(object instanceof String){
String temp = (String)object;
final int len = temp.length();
if (len > 0) {
if (len == NULL_STRING_LENGTH && NULL_STRING.equalsIgnoreCase(temp)) {
return false;
}
return true;
}else{
return false;
}
}else{
Optional<Object> optUserLogin = Optional.ofNullable(object);
if(optUserLogin.isPresent()){
return true;
}else{
return false;
}
}
}
/**
* 判断参数是否为null
* @param object 判断参数
* @return 如果object为空值(null)、空串("")或"null" 返回true,否则返回false
*/
public static boolean isNull(Object object){
if(object instanceof String){
String temp = (String)object;
final int len = temp.length();
if (len > 0) {
if (len == NULL_STRING_LENGTH && NULL_STRING.equalsIgnoreCase(temp)) {
return true;
}
return false;
}else{
return true;
}
}else{
Optional<Object> optUserLogin = Optional.ofNullable(object);
if(optUserLogin.isPresent()){
return false;
}else{
return true;
}
}
}
}
测试用例:
package util;
/**
* 测试用例
* @author fal
*/
public class TestMain {
public static void main(String[] args) {
testNullUtilIsNull();
}
public static void testNullUtilIsNotNull(){
String temp = null;
String temp2 = "";
String temp3 = "null";
String temp4 = "NULL";
String temp5 = "temp";
Integer integer = null;
Integer integer2 = 1;
System.out.println(NullUtil.isNotNull(temp));
System.out.println(NullUtil.isNotNull(temp2));
System.out.println(NullUtil.isNotNull(temp3));
System.out.println(NullUtil.isNotNull(temp4));
System.out.println(NullUtil.isNotNull(temp5));
System.out.println(NullUtil.isNotNull(integer));
System.out.println(NullUtil.isNotNull(integer2));
}
public static void testNullUtilIsNull(){
String temp = null;
String temp2 = "";
String temp3 = "null";
String temp4 = "NULL";
String temp5 = "temp";
Integer integer = null;
Integer integer2 = 1;
System.out.println(NullUtil.isNull(temp));
System.out.println(NullUtil.isNull(temp2));
System.out.println(NullUtil.isNull(temp3));
System.out.println(NullUtil.isNull(temp4));
System.out.println(NullUtil.isNull(temp5));
System.out.println(NullUtil.isNull(integer));
System.out.println(NullUtil.isNull(integer2));
}
}