Characteristics of the new null pointer exception killer Optional class Java8

Java8 new series we've covered Stream, Lambda expressions, DateTime date and time, at last, to explain the "NullPointerException" nemesis Optional class to ending.

background

As a developer with NullPointerException wits every day. Each parameter is received or obtained worth calling a method to determine what is null. A little attention, a null pointer exception is like a ghost appeared.

In this article we learn how to avoid Java8 null pointer exception by the Optional classes.

When not in use Optional first look at the class, how will we deal with in order to prevent NullPointerException.

public String getParentName(Person son) {
    if (son != null) {
        Person parent = son.getParent();
        if (parent != null) {
            return parent.getUsername();
        } else {
            return "--";
        }
    }

    return "--";
}

In order to prevent abnormal, we need to stop judging whether the object is null. But if the business logic is more complex, it will be the emergence of a large number of ifelse. Seemingly careful logic, but legibility is not high.

To solve the problem, the proposed method if the return type is set by returning an empty collection to avoid NullPointerException, took great pains in the Effective Java.

Look at the code above, what will become after use Optional.

public String getParentNameWithOptional(Person son) {
    return Optional.ofNullable(son).map(Person::getParent).map(Person::getUsername).orElse("--");
}

Control what code to see God not magical? !

Optional Class Profile

java.util.Optional The introduction of class a good solution to a null pointer exceptions, like the following statement:

public final class Optional<T> {}

java.util.Optional Class is a container object that encapsulates Optional values, Optional value may be null, if the value exists, calling isPresent () method returns true, calls the get () method gets the value.

By at the source code, it does not implement java.io.Serializable, it should be avoided in the class attribute, to prevent unexpected problems.

Optional addition to class, also extends Optional some common types of objects, such as: OptionalDouble, OptionalInt, OptionalLong. Usage is basically similar.

Optional class to understand by the following specific operations and functions.

Creating Optional objects

There are three ways to create an object Optional: empty (), of (), ofNullable (), are static methods.

If the object has no value Optional with empty () method.

Optional empty = Optional.empty();

If the determination value Optional object is not null, then of the available () method.

Optional stringOptional = Optional.of("Hello 公众号:程序新视界");

If the value is uncertain whether Optional object is null, available ofNullable (). Such as the above, uncertain whether the Person object is not null, to use the ofNullable () method. Of course, it can be passed directly to the null method.

Optional ofNullOptional = Optional.ofNullable(null);

In this case, the method by calling its isPresent Optional whether to see the value is null.

boolean bool = ofNullOptional.isPresent();
System.out.println(bool);

At this point if you call the get method to get the value directly, it will throw an exception.

ofNullOptional.get();

get Gets the value of Optional

Optional values ​​can be obtained by the get method, but if the value is null, an exception is thrown.

Optional ofNullOptional = Optional.ofNullable(null);
ofNullOptional.get();

Exception information:

java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)
...

In this case, a method requires additional auxiliary: isPresent (). The method may determine whether there are values ​​Optional, if it returns true, if not it returns false.

Optional ofNullOptional = Optional.ofNullable(null);
boolean bool = ofNullOptional.isPresent();
if(bool){
    ofNullOptional.get();
}

Optional map to get the value of

For the object operation may also be obtained by map value, beginning a simplified example is the case.

Optional<Person> sonOptional = Optional.ofNullable(son);
System.out.println(sonOptional.map(Person::getUsername));

map method, if there is value, then calling the mapping function to get its return value. If the return value is not null, then create a map that contains Optional return value as the map method returns a value, otherwise return empty Optional.

Optional flatMap get the value of

If there is value, Optional type returns the return value, otherwise return empty Optional. Similar methods flatMap and map. But flatMap The mapper return value must be Optional. The end of the call, flatMap will not result with Optional package.

Optional<Person> sonOptional = Optional.ofNullable(son);
sonOptional.flatMap(OptionalTest::getOptionalPerson);

Another method is called the current class of OptionalTest:

public static Optional<Person> getOptionalPerson(Person person){
    return Optional.ofNullable(person);
}

Optional orElse get the value of

orElse method, if a value is returned, otherwise a given value as the default value;

Optional.empty().orElse("--");

The above case will return "-."

Here, the arithmetic operation trinocular same effect.

str != null ? str : "--"

Optional orElseGet get the value of

Similarly orElseGet () method orElse () method of action, but a different way of generating default values. The method accepts a Supplier <extends T?> Interface function parameter, for generating a default value;

Optional.empty().orElseGet(() -> {
            String a = "关注";
            String b = "公众号:程序新视界";
            return a + b;
        });

Obviously, where it can handle more business logic.

Optional orElseThrow get the value of

orElseThrow () method and get () method is similar to when the value is null call will throw a NullPointerException, but the method can specify the type of exception thrown.

Optional.empty().orElseThrow(()-> new RuntimeException("请先关注公众号!"));

A print exception information is:

Optional.empty().orElseThrow(()-> new RuntimeException("请先关注公众号!"));

Analyzing and performs an operation

ifPresent method, the values ​​are determined and then printing to receive parameters Consumer <? super T> interface function.

Optional.of("公众号:程序新视界").ifPresent(System.out::println);

Of course, other complex operations may be performed in the function:

Optional.of("公众号:程序新视界").ifPresent((val)->{
            System.out.println("欢迎关注" + val);
        });

filter () method of filtering

filter () method can be used to judge whether an object Optional satisfies a given condition, the general conditions for filtering:

Optional.of("公众号:程序新视界").filter((val)->{
    return val.contains("程序新视界");
});
// 简化写法
Optional.of("公众号:程序新视界").filter((val)-> val.contains("程序新视界"));

Use Mistakes

Optional on the use of the following errors:

  • The correct method to use to create, not sure whether to try to choose ofNullable method is null.
  • Avoid use in member variables (the reasons already mentioned above);
  • Avoid isPresent method and get a direct call Optional object;

Finally, a possible difficult to understand, imagine if the first obtained by isPresent method exists and then decide whether to call the get method before ifelse judgment no different.

Java8 promote functional programming, the new API can be used in many functional programming represents, Optional class is one of them.

summary

So far, Java8 new features relevant content will come to an end.

Java8 new series of related articles:

No public concern "program New Horizons", reply "001" get the whole "Java8 new series," the PDF version.

Original link: " null pointer new for Java8 unusual nemesis Optional class "


New Horizons program : exciting and growth are not to be missed

New Horizons program - micro-channel public number

Guess you like

Origin www.cnblogs.com/secbro/p/11689773.html