当前位置:网站首页>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 .
边栏推荐
- Market status and development prospect prediction of global neutral silicone sealant industry in 2022
- Market status and development prospect prediction of the global forward fluorescent microscope industry in 2022
- 论文阅读_中文NLP_ELECTRA
- [research materials] annual report of China's pension market in 2021 - Download attached
- Why does I start with =1? How does this code work?
- Hj35 serpentine matrix
- Hire cashier (differential constraint)
- Notes | numpy-08 Advanced index
- [research materials] 2022q1 game preferred casual game distribution circular - Download attached
- I've seen a piece of code in the past. I don't know what I'm doing. I can review it when I have time
猜你喜欢
The usage of micro service project swagger aggregation document shows all micro service addresses in the form of swagger grouping
C language self-made Games: Sanzi (tic tac toe chess) intelligent chess supplement
[luatos sensor] 2 air pressure bmp180
The simple problem of leetcode: dismantling bombs
Learn to use the idea breakpoint debugging tool
Games101 Lesson 9 shading 3 Notes
《牛客刷verilog》Part II Verilog进阶挑战
Web security - CSRF (token)
Triangular rasterization
[PCL self study: filtering] introduction and use of various filters in PCL (continuously updated)
随机推荐
Leetcode simple question: check whether the string is an array prefix
【工具跑SQL盲注】
Contents of welder (primary) examination and welder (primary) examination in 2022
Symbol of array element product of leetcode simple problem
Concurrent operation memory interaction
第十九届浙江省 I. Barbecue
论文阅读_中文医疗模型_ eHealth
[tools run SQL blind note]
Oracle SQL table data loss
Without 50W bride price, my girlfriend was forcibly dragged away. What should I do
Leetcode simple question: check whether the array is sorted and rotated
MC Layer Target
Esp32-c3 learning and testing WiFi (II. Wi Fi distribution - smart_config mode and BlueIf mode)
[luatos sensor] 2 air pressure bmp180
Day 51 - tree problem
[luatos sensor] 1 light sensing bh1750
Market status and development prospects of the global autonomous marine glider industry in 2022
[XSS bypass - protection strategy] understand the protection strategy and better bypass
Literature reading_ Research on the usefulness identification of tourism online comments based on semantic fusion of multimodal data (Chinese Literature)
Truncated sentences of leetcode simple questions