Home > Back-end >  Java how to simplify the prevent NPE error code?
Java how to simplify the prevent NPE error code?

Time:03-20

 
(requestEntity==null | | requestEntity. GetBody ()==null)? "" : requestEntity. GetBody (). The toString ()


My code with this prevent NPE error code, want to ask what is the simple way to prevent the NPE in Java exception
There are several kinds of cope with the problem of NPE writing? Against the NPE chain writing?

CodePudding user response:

Basically is to use Optional,,, actually write up also is very long, and comparison of the original, however, the same line with Optional after look more clear,,,
 
Optional SomeMethod () {
.
}

String the use () {
Return someMethod ()
. The map (RequestEntity: : getBody)
//. The map (T: : toString)
.map Objects: the toString ()
OrElse (" ");
}

  • Related