Offer to come, dig friends take it! I am participating in the 2022 Spring Recruitment series -Debug recording task, click to view the details of the activity.

I. Problem Description:

Java. Lang. NullPointerException is one of our common development problems, take a look at you play several mistakes easily.

  1. Access properties of an empty object

  1. Empty property progressionequalshashcodeOr other object method calls

  1. Methods that pass NULL to the underlying type enter arguments

A method is called

public static void test(int userId) {
    System.out.println(userId);
}
Copy the code

Ii. Solutions:

There are three common solutions: add if, Optional, or compile @nonNULL annotations.

  1. Added if judgment, judgment logic is object! = null && object. Attributes as well! = null

    The specific code is as follows:

    UserDto userDto = new UserDto();
    if(userDto ! =null && Objects.equals(userDto.getUserId(), 1)) {
        test(userDto.getUserId());
    }
    Copy the code

    This method looks more complicated, in fact, very rigorous, simple. If there are many similar judgments in the project, general-purpose method wind encapsulation such as IntegerUtil and StringUtil can be done. You can also do some customized logic to prevent batch modification and reduce code changes. In fact, we also use tripartite toolkits such as hutool-util and Apache-common in development

  2. Optionally, execute the call method if it is not empty, or return the default value

    The specific code is as follows:

    // Execute only if it is not empty
    UserDto userDto = new UserDto();
    Optional.of(userDto.getUserId()).ifPresent(item -> {
        test(userDto.getUserId());
    });
    
    // Return the default value if null
    Integer userId = Optional.of(userDto.getUserId()).orElse(1);
    Copy the code

    Java 8 introduces the Optional class, which addresses the infamous NullPointerException. This is a wrapper class with Optional values, which means that the Optional class can contain objects as well as empty objects, providing a number of utility methods such as ifPresent and orElse. Optional is the cornerstone of functional programming in Java and a great syntactic sugar that Comes with Java 8.

  3. Increase compilation @ NonNull annotations (org. Springframework. Lang. NonNull)

    The code is as follows:

    public static void test(@NonNull Integer userId) {
        System.out.println(userId);
    }
    Copy the code

    I usually provide a public method, or some method calls, will use NonNull, Nullable to mark whether the parameter can be null, so it is convenient when I call at a glance whether the parameter can be null, and if the parameter is null, IDEA will be prompted during compilation, very convenient. In addition, the parameters of the Web API interface can be marked with some annotations in JSR303, whether they are empty or not, and then implemented by @vaild is also very convenient. For example, Spring MVC and Hibernate Validator provide a rich library for checking parameters. Special we can also define ourselves.

Iii. Summary:

This paper is simple and intuitive describes several common Java. Lang. NullPointerException scenarios and solutions. If you have similar experience can leave a message to discuss

NullPointerException is usually at run time, so maybe we’re going to select a data field, but the field is not required, However, NullPointerException will appear if the entity is not mapped during the query. So when you look at the code logic, you often need to make a compromise choice. In fact, in a project, it is good to find the balance.