The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
Java 是如何优雅地处理NPE问题的

1. preface

for Java For developers,null It's a troublesome type that can happen if you're not careful NPE (Empty pointer) problem. is also Java One of the important reasons why language is criticized. Before we eliminate the hateful NPE Before we ask, we want to review the concept of null in Java.

2. null in Java

translated from Oracle Java Documentation

There are two types in the Java language, one is basic types , the other is reference type。There is also a special type that has no name, namely expression null
due to null Types have no names, so it is impossible to declare as null variable of type or converted to null Type.
null reference isnull The only possible value for a type expression.
null References can be converted to any reference type.
In fact, programmers can ignorenullType, can be considerednullJust a special symbol that can be any reference type.

We can understand from the above description,In fact, null is just a keyword identifier. It is neither a type nor an object. It cannot be directly declared null and converted to null. It can only be referenced. null can be converted to any reference type. When a Java reference type object is referenced as null, it means that the current object does not reference the object and no memory is allocated for it. This is also the root cause of empty pointers when we call methods on objects without reference.
in most cases Java developers to use null It's meant to mean something that doesn't exist.

3. Solving NPE problems

Many times we have our own expectations about whether data exists, but this expectation cannot be directly controlled by us. The meaning expressed by a return value of null is not clear and too vague. It is often determined by whether or not null to avoid the empty pointer problem. So Google engineers worked on their Guava Tools class library designed Optional<T> to solve null Uncontrollable problems. that allows you to use null When, it can be used more easily and clearly null and help you avoid direct use null Problems brought.
Java 8 Incorporate this design. we can directly use Java provided Optional to solve the empty pointer problem. Next let's study Java 8 of Optional

4. Optional in Java 8

in Java 8 Optional Is a wrapper class for optional values. It doesn't just help us simplify NPE Dealing with problems, but also Java An important aid to functional programming. We're going to take it API Provide explanations to help you use them in actual development.

4.1 Optional Statement

Optional Declarations can only be made through static methods. It provides three static methods:

empty() Returns a value of null the Optional examples

  Optional<Object> empty = Optional.empty();

of(T) Returns a value that is not null the Optional examples

 Optional<String> nonNull = Optional.of("Felordcn");

ofNullable() Returns a value that may be null the Optional examples

 // value comes from other uncertain sources
 String value = SomeApi.source();
 //may be null 
 Optional<String> nullable = Optional.ofNullable(value);
 //may not be null 
 Optional<String>  hasValue = Optional.ofNullable(value);

4.2 other methods

isPresent() Returns if value exists true, otherwise return false 。if Optional Value is uncertain, this method can be used for safety verification

 Optional<String> nonNull = Optional.of("Felordcn");
  // true      
  boolean present =nonNull.isPresent();

get() obtain Optional If it is empty, it will be thrown NoSuchElementException abnormal

  // value comes from other uncertain sources
  String value = SomeApi.source();
  //may be null 
  Optional<String> nullable = Optional.ofNullable(value);
  // Felordcn      
  String str = nullable.get();

ifPresent(Consumer) If a value exists, the value is consumed by the function Consumer Consumption, otherwise do nothing. isPresent() enhanced version


      //Print the string without blank     
      nullable.ifPresent(System.out::println);

     //equivalent to
      if (nullable.isPresent()) {
                 System.out.println(nonNull);
      }

filter(Predicate) If the value satisfies the assertion function Predicate Return the Optional, otherwise return Optional.empty()

 Optional<String> nonNull = Optional.of("Felordcn");
 Optional<String> felord = nonNull.filter(s -> s.startsWith("Felord"));
 // str = "Felordcn"
 String str = felord.get();

map(Function) Gets the attribute of an element Optional 。if the property is null return Optional.empty() , otherwise return the corresponding value of Optional

 Optional<User> userOpt = Optional.ofNullable(user);
//If username is empty, it will be empty Optional  
 Optional<String> usernameOpt = userOpt.map(User::getUsername);

flatMap(Function) Sometimes we return Optional<Optional<T>> It is very inconvenient to handle. We need to expand the element. We can use this method to handle it. Refer to Stream Api the relevant method specified in

orElse(other) if Optional value exists, return Optional, otherwise specify one Optional

orElseGet(Supplier) if Optional value exists, return Optional, otherwise specify an execution Supplier Function to get the value

orElseThrow(Supplier<? extends Throwable>) if Optional value exists, return Optional, otherwise throw a specified Supplier Exception provided by function

4.3 New APIs in Java 9

or(Supplier) orElseGet Types of improvements. Not only return specific values, but you can return them functionally Optional

stream() will Optional and Stream open up

ifPresentOrElse(Consumer) ifPresent Methods provide consumption logic with values, while logic without values provides no entry. new method ifPresentOrElse it makes up for

5. Misunderstandings of Optional

Optional It smells good but you can't abuse it. A dangerous move is to Optional Passed to the method as an input parameter. Because the entry is uncontrollable, you cannot guarantee the entry Optional whether it is null。This is exactly contrary to Optional the original intention. So try to use it in expressions Optional or use it in the return value rather than in the parameters of the method Optional

6. summary

today Optional Give an explanation. from Optional The design intention is based on its common methods. We are also interested Optional in Java 9 The new API in. in addition Optional It is not a panacea, and only through reasonable use can its advantages be given full play. I hope today's article is useful to you.

read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/4450.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1

Comments0

Cocos系列情怀源码多套精美UI界面皮肤切换全国600子游戏(带控制)
Cocos series emotions source code, multiple sets of exquisite UI interfaces, skin switching across 600 sub-games across the country (with control)
Someone bought it 1 minute ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish