(requestEntity == null || requestEntity.getBody() == null) ? "" : requestEntity.getBody().toString()
我的代碼里充斥著這種防止NPE錯誤的代碼,想問java里有什么簡單的方法防止NPE例外
有幾種應對NPE問題的寫法?鏈式寫法怎么防NPE?
uj5u.com熱心網友回復:
基本上就是用Optional。。。其實寫起來也很長,不過和原本的對比,同樣換行后用Optional看起來比較清晰。。。
Optional<RequestEntity> someMethod() {
...
}
String use() {
return someMethod()
.map(RequestEntity::getBody)
// .map(T::toString)
.map(Objects::toString)
.orElse("");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/269007.html
標籤:Web 開發
