Optional of the new features of java8 --- Solve the problem of null pointers

Optional is used to simplify the judgment of null values ​​in Java to prevent various null pointer exceptions. Optional actually encapsulates a variable, it contains an attribute value, which is actually the value of this variable.

1 Creation
Its constructors are all private types, so to initialize an Optional object cannot be created through its constructor. It provides a series of static methods for constructing Optional objects:
1.1 empty is
used to create an empty Optional object; its value attribute is Null.
Such as: Optional o = Optional.empty();
1.2 of
constructs an Optional object based on the value passed in;
the value passed in must be a non-null value, otherwise if the value passed in is a null value, a null pointer exception will be thrown.
Use: o = Optional.of("test");
1.3 ofNullable
constructs an Optional object based on the incoming value. The
incoming value can be a null value. If the incoming value is a null value, the result returned by empty is the same .
2 Method
3 Use scenario
3.1 Use after judging that the result is not empty
If a function may return a null value, the past practice:

String s = test();
if (null != s) {
    
    
    System.out.println(s);
}

The current writing can be:

Optional<String> s = Optional.ofNullable(test());
s.ifPresent(System.out::println);

At first glance, the code complexity is almost or even slightly increased; then why do you want to do this?
Under normal circumstances, when we use a function to return a value, the first step is to analyze whether the function will return a null value; if there is no analysis or the result of the analysis is biased, the function will throw a null value. If no detection is done, then a null pointer exception will be thrown accordingly!
With Optional, we don't need to do this detection when we are not sure. All the Optional objects will help us to complete the detection. All we have to do is to deal with it in the above-mentioned way.
3.2 Provide a default value when
a variable is empty If you want to judge that a variable is empty, use the provided value, and then perform certain operations on this variable; the
past practice:

if (null == s) {
    
    
    s = "test";
}
System.out.println(s);

Current practice:

Optional<String> o = Optional.ofNullable(s);
System.out.println(o.orElse("test"));

3.3 Throw an exception when the variable is empty, otherwise use the old
way of writing:

if (null == s) {
    
    
    throw new Exception("test");
}
System.out.println(s);

Now write:

Optional<String> o = Optional.ofNullable(s);
System.out.println(o.orElseThrow(()->new Exception("test")));

Guess you like

Origin blog.csdn.net/Wangdiankun/article/details/114899433