尽量少的用null,NPE是万恶之源,可以使用java8提供的Optional,对应scala中是option,可以参考OptionalUtil中的方法。下面给几个对比的example:
eg:
使用前:
T t= service.get();
if(t== null ){
throw new Exception("object not exist");
}
使用后:
T t= OptionalUtil.get(() -> ervice.get()).orElseThrow(() -> new throw new Exception("object not exist"));
下面就可以安全的使用 t 而不需要考虑它是否为null,因为它一定不为null,这也是Optinal的意义所在。
一个大大的彩蛋:https://mp.youkuaiyun.com/postedit/82686446
附 OptonalUtil代码:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
import java.util.function.Supplier;
/**
* Created by pandechuan on 2018/1/5.
*/
public class OptionalUtil {
private static final Logger logger = LoggerFactory.getLogger(OptionalUtil.class);
/**
* 防止取值NPE方法
*/
public static <T> Optional<T> get(Supplier<T> supplier) {
T result = supplier.get();
return Optional.ofNullable(result);
}
public static Optional<Integer> stringToInt(String s) {
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
logger.error("", e);
return Optional.empty();
}
}
public static Optional<Long> stringToLong(String s) {
try {
return Optional.of(Long.parseLong(s));
} catch (NumberFormatException e) {
logger.error("", e);
return Optional.empty();
}
}
public static void main(String[] args) {
// Integer a = null;
// Optional<Integer> integerOptional = OptionalUtil.get(() -> a);
// System.out.println(integerOptional.isPresent());
// System.out.println(integerOptional.toString());
//
// List<String> list = Lists.newArrayList("1265", "f", " 5 ","89");
// List<Integer> intList = list.stream().map(OptionalUtil::stringToInt).filter(e -> e.isPresent()).map(e -> e.get()).collect(Collectors.toList());
// intList.forEach(System.out::println);
}
}