Null-pointer exceptions are probably the most common exceptions in code writing. In plain English, a null-pointer exception is when you take a nonexistent object and access its member properties or methods. Let’s look at the following code for a moment:
public static String getString() {
returnnull; } public static void main(String[] args) {// Return null String STR = getString(); System.err.println(str.length()); }Copy the code
It is obvious that the result of the program is running above must be ruled out annoying Java. Lang. NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at org.springframework.web.SpringServletContainerInitializer.main(SpringServletContainerInitializer.java:187)
Copy the code
However, it’s not the null pointer itself that’s so scary. What’s scary is the naming. We know that there is a possibility of a null pointer exception, but we don’t know or can’t predict it in advance, as shown in the code snippet above.
Is there a way to identify blocks of code that will throw NullPointerExceptions in advance and then do something about it? The answer is yes. I’m going to talk about some of the common methods of air defense, but notice, this is not a drill, this is not a drill, this is not a drill. Ha ha!
- 1. Use annotations to indicate whether a parameter or method return value is null
- 2. Use Java8
Optional
Class declares our API
Here I will discuss one by one (take Eclipse as an example for IDE) :
Preprocessing:
First we need to enable annotation-based checking in Eclipse, in Windows->Preference->Java->Compiler->Errors/Warnings->Null Analysis, as shown below:
1. Use annotations to indicate whether a parameter or method return value is null
Both JSR 303/305 and Spring provide annotations as follows:
- 1. JSR 303/305:
@Nonnull
,@Nullable
- 2, Spring:
@NonNull
,@Nullable
After Eclipse starts null checking, to make the @nullable annotation take effect, you need to configure the annotation’s full path type to Use default Annotations for NULL Sercispots as shown in the following figure:
After the configuration is complete, look at the following code:
/** * indicates that the returned value may be null * @return
*/
@Nullable
public static String getString() {
returnnull; } /** * the argument cannot be empty * @param STR * @return
*/
public static String getName(@NonNull String str) {
returnnull; } public static void main(String[] args) {// Return null String STR = getString(); System.err.println(str.length()); // The argument is null getName(null); }Copy the code
This makes it easy to see what code might be empty. Of course, the IDE supports scanning JSR specification annotations. Spring’s @nonNULL and @nullable annotations are also implemented based on JSR annotations and can be used to declare methods, fields, or parameters.
Second, the Optional
Java8 provides a class that models null called Optional. We can think of it as a container that holds either the method return value or the method parameter value, and if the method return value is null or the parameter value is null, then it returns an empty container object. Take a look at the following code:
/** * indicates that the returned value may be null * @return
*/
public static Optional<String> getString() {// Return an empty container with nothing in itreturnOptional.empty(); } /** * the argument cannot be empty * @param STR * @return
*/
public static String getName(Optional<String> str) {
returnstr.get(); } public static void main(String[] args) {// Return option.empty () Optional<String> Optional = getString(); // Return the value of orElse if the container is empty, otherwise return the value of orElse. String Value = optional.orElse("otherValue"); OtherValue system.err. Println (value); // The parameter is null getName(Optional. Of ("value"));
}
Copy the code
The Optional class makes it easy to model values that may return NULL, and there are a number of useful methods in Optional that allow us to pass in a lambda expression for processing.
conclusion
- 1. If you just want to handle null exceptions that may occur in your code logic, then I actually think it is more convenient to use IDE with annotations
Optional
That’s ok - 2. If we want to provide an external API, I would declare the API member attribute and method return value as
Optional
This is probably better because it is obvious that the API method signature may return a null value and the user only needs to use oneOptional
Can receive! - 3. If you want to reduce empty exceptions, the key is to improve your coding ability! A straight foot is not afraid of a crooked shoe.