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 use Optional to handle null type exception reports in Java

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the knowledge about "how to use Optional to handle null type exception errors in Java". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to handle these situations! I hope you can read carefully and learn something!

Talk about NullPointerException

Compared to Java development, seeing NullPointerException is definitely no stranger, and it can be said that seeing it is abhorrent. When you develop, you think that there will be no NullPointerException exception, and finally to the production environment, you will be surprised. If(null != 0), then the object is empty. xxx), or use some tool classes, such as: if(ObjectUtils.isEmpty(xxx)), you can see that this kind of processing will make our code very bloated, and we may have to do this when encountering an object.

Using the Optional class avoids using a bunch of ifs in your program to handle nulls. The following table lists the methods in the Optional class:

method name description empty Returns an empty Optional instance of wrapping the specified value with Optional, if the value is null, throws NullPointerException ofNullable wraps the specified value with Optional, if the value is null, returns an empty Optional object get If the value exists, returns the value, otherwise throws NullPointerException isPresent checks whether the value exists, returns true, otherwise returns falseifPresent If the value exists, executes the method call using the value, Otherwise do nothing filter If the value exists and satisfies the predicate provided, return an Optional object containing the value, otherwise return an empty Optional object map If the value exists, perform the mapping function call provided on the value flatMap If the value exists, perform the mapping function call provided on the value, return a value of type Optional, otherwise return an empty Optional object orElse If the value exists, return it Otherwise returns the specified value orElseGet returns the value generated by the specified Supplier interface if it exists orElseThrow returns the value if it exists otherwise throws an exception generated by the specified Supplier interface

Here are a few ways to use the above methods in detail.

2.1 emptyOptional user = Optional.empty();

Create an empty Optional object

2.2 ofUser user = null;Optional optional = Optional.of(user);

If user is empty, NullPointerException is reported directly, so this method is rarely used.

2.3 ofNullableUser user = null;Optional optional = Optional.ofNullable(user);

If user is empty, an empty Optional object is returned

2.4 getUser user = null;Optional optional = Optional.ofNullable(user);optional.get();

Get value from Optional, throw exception if value does not exist: java.util.NoSuchElementException: No value present

2.5 isPresentUser user = null;Optional optional = Optional.ofNullable(user);optional.isPresent();

The above example returns false, and returns true if user is not empty.

2.6 ifPresentUser user = null;Optional optional = Optional.ofNullable(user);optional.ifPresent(us->{ //user is not empty, execute});2.7 filterUser = new User();user.setName("small A");boolean result = Optional.ofNullable(user).filter(us -> "small A".equals(us.getName())).isPresent();

Returns true if user name is small A, false otherwise

2.8 mapUser = new User();user.setName("Small A");String name = Optional.ofNullable(user).map(User::getName).get();

If user is not empty, extract the name attribute and use get() to get it. Here, if name is empty, an exception will be reported, so usually default values are specified or custom exceptions are thrown.

String name = Optional.ofNullable(user).map(User::getName).orElse("");

or

String name = Optional.ofNullable(user) .map(User::getName) .orElseThrow(()->new RuntimeException("User name cannot be empty"));2.9 flatMap

This method is generally used to obtain an attribute of another class from the class. For example, there are students in a class, and the students have addresses. Now you need to obtain the address of a student in this class. According to the previous writing:

Address address = new Address();address.setAddr("Tianhe District");Student = new Student();student.setName("Small A");student.setAddress(address);Grade grade = new Grade();grade.setName("Grade 3 Class 2");grade.setStudent(student);if(! ObjectUtils.isEmpty(grade)){ Student student1 = grade.getStudent(); if(! ObjectUtils.isEmpty(student1)){ Address address1 = student1.getAddress(); if(! ObjectUtils.isEmpty(address1)){ System.out.println(address1.getAddr()); } }}

In order not to program problems, will write a lot of if to judge, the following flatMap to see how to achieve:

Optional.ofNullable(grade) .flatMap(g->Optional.ofNullable(g.getStudent())) .flatMap(s->Optional.ofNullable(s.getAddress())) .map(Address::getAddr) .orElse("")

or

Optional.ofNullable(grade) .map(Grade::getStudent) .map(Student::getAddress) .map(Address::getAddr) .orElse("")2.10 orElseOptional.ofNullable(grade).orElse(new Grade());2.11 orElseGetOptional.ofNullable(grade).orElseGet(()->new Grade());2.12 orElseThrowOptional.ofNullable(grade).orElseThrow(()->new RuntimeException("Class cannot be empty"));

The use of all methods of the Optional class above is listed.

"How to use Optional to handle null type exception errors in Java" is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

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