Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the NPE problem with Optional in JAVA8

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how JAVA8 uses Optional to solve NPE problems". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to solve the NPE problem with Optional in JAVA8".

Introduction

NPE (NullPointerException) is the most common exception for debuggers. Google there is a lot of discussion about whether the method should return null or new an empty object.

At the beginning of the article, let's talk about the NPE problem, the NPE problem is the NullPointerException. Suppose we have two classes whose UML class diagram is shown in the following figure

In this case, the code is as follows:

User.getAddress () .getProvince ()

In this way, when user is null, it is possible to report an NullPointerException exception. In order to solve this problem, the following methods are used:

If (username null) {Address address = user.getAddress (); if (addressworthy null) {String province = address.getProvince ();}}

This kind of writing is relatively ugly, in order to avoid the above ugly writing, let the ugly design become elegant. JAVA8 provides the Optional class to optimize this writing, which is explained in more detail in the following body

API introduction

First introduce API, unlike other articles, this article takes an analogical approach, combined with the source code. Unlike other articles, API is listed one by one, so that people can not find the main points.

(1) Optional (T value), empty (), of (T value), ofNullable (T value)

There is a correlation between these four functions, so they are put in a group for memory.

Just to be clear, Optional (T value), that is, the constructor, is private-authorized and cannot be called externally. The remaining three functions are public permissions for us to call. Then, the essence of Optional is that a real value is stored internally, and when it is constructed, it is directly determined whether the value is empty or not. Well, that's still a little abstract. Go directly to the source code of the Optional (T value) constructor, as shown in the following figure

So, the source code for of (T value) is as follows:

Public static Optional of (T value) {return new Optional (value);}

In other words, the constructor is called inside the of (T value) function. From the source code of the constructor, we can draw two conclusions:

(1) the Optional object constructed by the of (T value) function will still report NullPointerException when the value is empty.

(2) the Optional object constructed by the of (T value) function can construct the Optional object normally when the Value value is not empty.

In addition, the Optional class also maintains an object with value as null, which probably looks like the following

Public final class Optional {/ / omitted. Private static final Optional EMPTY = new Optional (); private Optional () {this.value = null;} / / omitted. Public static Optional empty () {@ SuppressWarnings ("unchecked") Optional t = (Optional) EMPTY; return t;}}

The purpose of empty (), then, is to return the EMPTY object.

Well, after laying the groundwork, it can be said that ofNullable (T value) plays a role, with the source code:

Public static Optional ofNullable (T value) {return value = = null? Empty (): of (value);}

The difference from of (T value) is that when the value is null, of (T value) will report a NullPointerException exception; ofNullable (T value) will not throw Exception,ofNullable (T value) directly return an EMPTY object.

Does that mean that we only use the ofNullable function instead of the of function in the project?

No, a thing exists so naturally it has the value of existence. When we are running, we do not want to hide NullPointerException. Instead, report it immediately, in which case the Of function is used. But I have to admit, such scenes are really rare. Bloggers have only used this function when writing junit test cases.

(2) orElse (T other), orElseGet (Supplier other) and orElseThrow (Supplier exceptionSupplier)

These three functions are memorized in groups and are called when the value passed in by the constructor is null. The use of orElse and orElseGet is shown below, which is equivalent to giving a default value when the value value is null:

@ Test public void test () {User user = null; user = Optional.ofNullable (user) .orElse (createUser ()); user = Optional.ofNullable (user) .orElseGet (()-> createUser ());} public User createUser () {User user = new User (); user.setName ("zhangsan"); return user;}

The difference between the two functions: when the user value is not null, the orElse function will still execute the createUser () method, while the orElseGet function will not execute the createUser () method, so you can test it yourself.

As for orElseThrow, when the value is null, an exception is thrown directly. The usage is as follows:

User user = null; Optional.ofNullable (user) .orElseThrow (()-> new Exception ("user does not exist")

(3) map (Function mapper) and flatMap (Function mapper)

These two functions are put in a set of memories, and these two functions do the operation of converting values.

Go directly to the source code, as follows:

Public final class Optional {/ / omitted. Public Optional map (Function

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report