当前位置:网站首页>Objects. Requirenonnull method description
Objects. Requirenonnull method description
2022-07-03 04:54:00 【Archie_ java】
When writing code ,Idea We are often reminded that we can use this method to check the non null parameters , The source code of this method is also very simple , As shown below :
/** * Checks that the specified object reference is not {@code null}. This * method is designed primarily for doing parameter validation in methods * and constructors, as demonstrated below: * <blockquote><pre> * public Foo(Bar bar) { * this.bar = Objects.requireNonNull(bar); * } * </pre></blockquote> * * @param obj the object reference to check for nullity * @param <T> the type of the reference * @return {@code obj} if not {@code null} * @throws NullPointerException if {@code obj} is {@code null} */
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
The method is Objects Class , Objects Class is a Java Static class , It contains a lot of Java Tool method , Its methods are all static methods , The class description document is as follows :
/** * This class consists of {@code static} utility methods for operating * on objects. These utilities include {@code null}-safe or {@code * null}-tolerant methods for computing the hash code of an object, * returning a string for an object, and comparing two objects. * * @since 1.7 */
public final class Objects {
...
}
It can be seen that , This class also includes many tools and methods for class operations , For example, compare whether two classes are equal , Computing class Hash Code Other methods , This class will have the opportunity to learn and introduce in the future .
go back to requireNonNull() This method , Its source code implementation is very simple , Just made a simple judgment , If the element to be judged is null, Return null pointer exception NullPointerException, Otherwise, directly return the corresponding object .
This seems like a redundant operation , Because if we try to call a method of an empty object , It will also be thrown out NullPointerException Runtime exception , So why do we need to make such an inspection at one stroke ? The problem is StackOverflow Someone answered on Why should one use Objects.requireNonNull?.
After reading their answers , It can be summarized as follows :
First , You can see from the name of this method , The scenario used in this method is , When we use the method of an object , The normal running state should ensure that the reference of this object is not empty , If this object is empty , There must be something wrong somewhere else , So we should throw an exception , We should not handle this non empty exception here .
secondly , This involves a very important programming idea , Namely Fail-fast thought , Which translates as , Make mistakes as early as possible , Don't wait until we are halfway through a lot of work before throwing an exception , This is likely to make some variables in abnormal states , More errors occur . This is also requireNonNull The design idea of this method , Let mistakes happen as soon as possible . Using this method , We explicitly throw exceptions , When something goes wrong , We immediately throw an exception .
StackOverflow An answer in gives a specific example to answer this question , For example, there is a class like this :
public class Dictionary {
private final List<String> words;
private final LookupService lookupService;
public Dictionary(List<String> words) {
this.words = this.words;
this.lookupService = new LookupService(words);
}
public boolean isFirstElement(String userData) {
return lookupService.isFirstElement(userData);
}
}
public class LookupService {
List<String> words;
public LookupService(List<String> words) {
this.words = words;
}
public boolean isFirstElement(String userData) {
return words.get(0).contains(userData);
}
}
here , Two classes are inclusive relationships , Incoming List The parameter is not checked for non null . If we are careless in Dictionary In the construction method of null, As shown below :
Dictionary dictionary = new Dictionary(null);
// exception thrown lately : only in the next statement
boolean isFirstElement = dictionary.isFirstElement("anyThing");
There are no exceptions when we construct , But when we call methods , Will throw out NPE:
Exception in thread "main" java.lang.NullPointerException
at LookupService.isFirstElement(LookupService.java:5)
at Dictionary.isFirstElement(Dictionary.java:15)
at Dictionary.main(Dictionary.java:22)
JVM Tell us , In execution return words.get(0).contains(userData) In this sentence , Something is wrong , But this anomaly is very ambiguous , From the error message , There are many possible reasons for this exception , Because words It's empty , still words.get(0) It's empty ? Or both are empty ? This is not clear . meanwhile , We can't be sure which link of these two classes went wrong , These are not clear , Give us the program debug Caused great difficulties .
However , When we implement :
public Dictionary(List<String> words) {
this.words = Objects.requireNonNull(words);
this.lookupService = new LookupService(words);
}
In this way , When we execute the construction method , It will definitely throw an error .
// exception thrown early : in the constructor
Dictionary dictionary = new Dictionary(null);
// we never arrive here
boolean isFirstElement = dictionary.isFirstElement("anyThing");
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at com.Dictionary.(Dictionary.java:15)
at com.Dictionary.main(Dictionary.java:24)
So let's do debug It's much clearer when , Less detours .
besides , The function of this method is also a clear and ambiguous difference , Using this method means that we have made this judgment clearly , In fact, it is used by ourselves if-else It's the same to judge , Only this tool class simplifies such operations , Make our code look simpler , More readable .
Besides , requireNonNull Method has an overloaded method , You can provide an error message , For us debug Show when . When we use this reference , It should be ensured that it is not empty , If not , Will throw an exception to tell us that something else has gone wrong , There is a null pointer exception . The implementation of this method overload is as follows :
/** * Checks that the specified object reference is not {@code null} and * throws a customized {@link NullPointerException} if it is. This method * is designed primarily for doing parameter validation in methods and * constructors with multiple parameters, as demonstrated below: * <blockquote><pre> * public Foo(Bar bar, Baz baz) { * this.bar = Objects.requireNonNull(bar, "bar must not be null"); * this.baz = Objects.requireNonNull(baz, "baz must not be null"); * } * </pre></blockquote> * * @param obj the object reference to check for nullity * @param message detail message to be used in the event that a {@code * NullPointerException} is thrown * @param <T> the type of the reference * @return {@code obj} if not {@code null} * @throws NullPointerException if {@code obj} is {@code null} */
public static <T> T requireNonNull(T obj, String message) {
if (obj == null)
throw new NullPointerException(message);
return obj;
}
for example , We are Android Can be used as follows :
String username = Objects.requireNonNull(textInputLayoutUsername.getEditText(), "TextInputLayout must have an EditText as child").getText().toString();
This is a PI TextInpuLayout How to get user input , Usually use TextInputLayout Wrap a EditText To receive user input , So we need to pass TextInputLayout Of getEditText() Method to get the corresponding EditText, If there is a problem with our layout , The method may return null, So we can use the above method , Throw an explicit exception , If there is a problem at runtime , We can also quickly know that it is because of us TextInputLayout Can't get EditText And make mistakes .
边栏推荐
- 2022 Shandong Province safety officer C certificate examination content and Shandong Province safety officer C certificate examination questions and analysis
- 普通本科大学生活避坑指南
- 论文阅读_中文医疗模型_ eHealth
- Leetcode simple question: check whether the string is an array prefix
- Day 51 - tree problem
- ZABBIX monitoring of lamp architecture (3): zabbix+mysql (to be continued)
- Silent authorization login and registration of wechat applet
- Market status and development prospect prediction of the global autonomous hybrid underwater glider industry in 2022
- document. The problem of missing parameters of referer is solved
- Compile and decompile GCC common instructions
猜你喜欢

Introduction to JVM principle

Symbol of array element product of leetcode simple problem

2022 Shandong Province safety officer C certificate examination content and Shandong Province safety officer C certificate examination questions and analysis

Use Sqlalchemy module to obtain the table name and field name of the existing table in the database

Oracle SQL table data loss

5-36v input automatic voltage rise and fall PD fast charging scheme drawing 30W low-cost chip
![[set theory] relationship properties (symmetry | symmetry examples | symmetry related theorems | antisymmetry | antisymmetry examples | antisymmetry theorems)](/img/34/d195752992f8955bc2a41b4ce751db.jpg)
[set theory] relationship properties (symmetry | symmetry examples | symmetry related theorems | antisymmetry | antisymmetry examples | antisymmetry theorems)

Review the old and know the new: Notes on Data Science
![[clock 223] [binary tree] [leetcode high frequency]: 102 Sequence traversal of binary tree](/img/0f/bc8c44aee7a2c9dccac050b1060017.jpg)
[clock 223] [binary tree] [leetcode high frequency]: 102 Sequence traversal of binary tree

带有注意力RPN和多关系检测器的小样本目标检测网络(提供源码和数据及下载)...
随机推荐
Notes | numpy-10 Iterative array
Shell script Basics - basic grammar knowledge
2022 chemical automation control instrument examination summary and chemical automation control instrument certificate examination
逆袭大学生的职业规划
SSM framework integration
Flutter monitors volume to realize waveform visualization of audio
Market status and development prospect prediction of global SoC Test Platform Industry in 2022
RT thread flow notes I startup, schedule, thread
Market status and development prospect prediction of the global autonomous hybrid underwater glider industry in 2022
"Niuke brush Verilog" part II Verilog advanced challenge
Small sample target detection network with attention RPN and multi relationship detector (provide source code, data and download)
【工具跑SQL盲注】
The consumption of Internet of things users is only 76 cents, and the price has become the biggest obstacle to the promotion of 5g industrial interconnection
Learn to use the idea breakpoint debugging tool
Triangular rasterization
C Primer Plus Chapter 10, question 14 3 × 5 array
[research materials] 2021 annual report on mergers and acquisitions in the property management industry - Download attached
Coordinatorlayout appbarrayout recyclerview item exposure buried point misalignment analysis
Market status and development prospects of the global autonomous marine glider industry in 2022
Esp32-c3 learning and testing WiFi (II. Wi Fi distribution - smart_config mode and BlueIf mode)