Excerpt: https://www.cnblogs.com/kyoner/p/12101005.html
Optional class with a null pointer exception
First, what is the null pointer exception
When the program needs to return object instance null
throws a null pointer exception ( NullPointerException
abbreviated the NPE ). Include the following:
- Call an
null
object instance method - Access to or modification of
null
the object's field - To obtain an array of
null
length when - Access or modification to the array
null
index value of - Throw an
Throwable
objectnull
exception of
Although the code is difficult to foolproof to avoid all NPE, but we should try to reduce. So some defensive programming skills, you can control the NPE on a good level.
Null pointer Case
1. Call service method's return value objects
In a method not clear whether the return value returned present null
case, the object used as the return value.
People people = new People();
People user = people.getUser("name");
String name = user.getName();
System.out.println(name);
In the example above
people.getUser("name");
the object it is not clear whether the call returnsnull
, the object's direct call back method causes NPE.
2. Automatic packaging value unboxed
In the packaging object is null
the case, the automatic unpacking operation.
Integer a = null;
int b = a;// System.out.println(1 == a);
In the above example the packaging class object
a
initialization value is definednull
, in thea
assignment of basic data types tob
time, and the basic data types1
when equality of logic operations are carried out automatically unpacking operation,a
asnull
when the result NPE.
3. iterating over collections and arrays empty object
In the collection or array is unclear whether the null
time, they are traversal operation.
List<String> list = null;// String[] list = null;
for (String string : list) {
System.out.println(string);
}
In the method returns a collection or array and their definitions, as long as there is
null
caused when NPE (excluding the length of the array and a set of 0), a traverse.
Example 4. Spring no injection of
When using the Spring framework, if the injection object instance fails, then the object is null
.
public class BeanExample {
@Autowired private BeanProvider beanProvider; public void run() { this.beanProvider.sayHello(this.name, this.age); } }
When the improper operation because
beanProvider
there is no injection, the callsayHello()
resulting in NPE time approaches.
The value of ConcurrentHashMap and Hashtable
Some do not support the null
collection of value added null
value elements, such as ConcurrentHashMap
and Hashtable
.
ConcurrentHashMap<String, String> map = new ConcurrentHashMap();
map.put("a", null);
Hashtable<String, String> hashtable = newHashtable<>();
hashtable.put("a", null);
These underlying collection
put(K key,V value)
method,key
orvalue
for thenull
case where the result NPE.
Second, how to prevent the null pointer exception
Since it is difficult to avoid NPE, we have to find ways to solve. Both have good coding habits, but also to the careful control of the business.
1. Normal processing
NPE carried out for the common defense against business method calls, you can simply add a non-empty judgment.
People people = new People();
People user = people.getUser("name");
if (user != null) {
String name = user.getName();
System.out.println(name);
}
2. When defining the object initialization
Define objects in their own time, pay attention to the initialization value for the Can null
.
// String str = "";
// 初始化为空字符串People people = newPeople();
// 初始化为对象
People user = people.getUser("name");
3. Use equals () method note
Known non-null object caller, such as constant values, as a caller enumeration value, avoiding the use of the object to invoke the method unknown, which can effectively prevent NPE.
String str = "123", string = null;
System.out.println(str.equals(string));
4. Use valueOf () instead of toString () method
Using the toString()
method to use to call the object methods, and the object is not clear whether in null
the case, that throws NPE. Using the valueOf()
method avoids the use of unknown objects to invoke methods to avoid.
People people = null;
System.out.println(String.valueOf(people)); // print:null
System.out.println(people.toString()); // NPE
5. The method of determining non-empty open source library
Recommended major open source library of StringUtils
string and CollectionUtils
a set of tools such as non-empty judgment.
String str = null;
List<String> list = null;
if (!StringUtils.isEmpty(str)) {
System.out.println(str);
}
if (!CollectionUtils.isEmpty(list)) {
System.out.println(list);
}
The method returns an empty set or a null array
In the process returns empty array and an empty rather than returning null
, JDK own Collections
set of tools provides several empty set of definitions.
public People[] getUsersArr() {
return new People[]{};
}
public List<People> getUsers() { // return Collections.emptyMap(); // return Collections.emptySet(); return Collections.emptyList(); }
7. Define whether the database field is empty
In some particular field may be determined according to whether the service is empty, and provided a reasonable default value. For example: represents the state of the business field.
CREATE TABLE user{ ... status NOT NULL DEFAULT 0 ...}
8. Optional use of Class JDK1.8
Providing preventing NPE particular container, it will be mentioned later after JDK1.8.
Three, Optional
Optional
It may comprise a null
or a non- null
container object. According to the source code analysis features:
Method 1. Definitions
1.1 empty
Returns an empty Optaional
instance, there are no values in this example.
public static<T> Optional<T> empty() { @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; }
1.2 of
A return value can not empty Optional
instance, is in this example null
when thrown NPE.
public static <T> Optional<T> of(T value) { return new Optional<>(value); } private Optional(T value) { this.value = Objects.requireNonNull(value); }
1.3 ofNullable
May return a null value Optional
example, the value in this example null
returns an empty time Optaional
instance.
public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); }
2. Functional Method
2.1 isPresent
If there is value exists, returns true
, otherwise it returns false
.
People people = new People();
System.out.println(Optional.ofNullable(people).isPresent());// print: true
people = null;
System.out.println(Optional.ofNullable(people).isPresent());// print: false
2.2 get()
If there is value exists, the return value, otherwise throw NoSuchElementException
.
People people = new People();
System.out.println(Optional.ofNullable(people).get());// print: People@61bbe9ba
people = null;
System.out.println(Optional.ofNullable(people).get());// print: Exception in thread "main" java.util.NoSuchElementException: No value present
Do not use this method to get the object.
2.3 orelse
If there exists a value, the return value, otherwise the orElse
method parameters may be used to define a default value.
String str = null;
String result = Optional.ofNullable(str).orElse("default");//print:default
System.out.println(result);
2.4 orElseGet
If there is value exists, the return value, otherwise the provider function, the function can return values to define default values.
String str = null;
String result = Optional.ofNullable(str).orElseGet(() -> "ajn");//print:ajn
System.out.println(result);
2.5 orElseThrow
If there is value exists, the return value, otherwise abnormal function interface parameter.
String str = null;
String result = Optional.ofNullable(str).orElseThrow(IllegalArgumentException::new);// print: Exception in thread "main" java.lang.IllegalArgumentException
System.out.println(result);
More details about the function interface, focusing on Java Functional Programming
2.6 ifPresent
If there is value exists, the function interface method parameters provided will be processed, otherwise does nothing.
Optional.ofNullable(getPeople()).ifPresent(people -> {
System.out.println("the people is nut null: " + people);
});
The above code is equivalent to:
People people = getPeople();
if (people != null) {
System.out.println("the people is nut null: " + people);
}
2.7 filter
If there exists a value, and the value in line with the conditions given function returns the current Optional
, otherwise an empty Optaional
instance, can be used to filter the special value.
String name = "AiJiangnan";// 给定的条件是字符串包含Ai
String result = Optional.of(name).filter(str -> str.contains("Ai")).orElse("字符串不包含Ai");
System.out.println(result);
2.8 map
If there exists a value, type value can be converted into the other type, and converts the return type of Optional
example, otherwise an empty Optaional
instance, it can be judged chain empty, very practical.
People people = null;
String result = Optional.ofNullable(people)
.map(People::getName)
.map(String::toUpperCase)
.orElse("default");
System.out.println(result);
Only when the
people
object is notnull
, andpeople.getName()
is notnull
, only to return name to all uppercase string, otherwise returns default.
2.9 flatMap
If there exists a value, type value can be converted into the other type, but can only turn to Optional
examples, otherwise an empty Optaional
instance. The method and map
method similar, but the method returns Optional
instance returned by the function parameters.
People people = new People();
people.setName(" ajn ");
String result = Optional.ofNullable(people)
.flatMap(peo -> Optional.ofNullable(peo.getName()))
.flatMap(str -> Optional.of(str.toUpperCase()))
.orElse("default");
System.out.println(result);
First, what is the null pointer exception
When the program needs to return object instance null
throws a null pointer exception ( NullPointerException
abbreviated the NPE ). Include the following:
- Call an
null
object instance method - Access to or modification of
null
the object's field - To obtain an array of
null
length when - Access or modification to the array
null
index value of - Throw an
Throwable
objectnull
exception of
Although the code is difficult to foolproof to avoid all NPE, but we should try to reduce. So some defensive programming skills, you can control the NPE on a good level.
Null pointer Case
1. Call service method's return value objects
In a method not clear whether the return value returned present null
case, the object used as the return value.
People people = new People();
People user = people.getUser("name");
String name = user.getName();
System.out.println(name);
In the example above
people.getUser("name");
the object it is not clear whether the call returnsnull
, the object's direct call back method causes NPE.
2. Automatic packaging value unboxed
In the packaging object is null
the case, the automatic unpacking operation.
Integer a = null;
int b = a;// System.out.println(1 == a);
In the above example the packaging class object
a
initialization value is definednull
, in thea
assignment of basic data types tob
time, and the basic data types1
when equality of logic operations are carried out automatically unpacking operation,a
asnull
when the result NPE.
3. iterating over collections and arrays empty object
In the collection or array is unclear whether the null
time, they are traversal operation.
List<String> list = null;// String[] list = null;
for (String string : list) {
System.out.println(string);
}
In the method returns a collection or array and their definitions, as long as there is
null
caused when NPE (excluding the length of the array and a set of 0), a traverse.
Example 4. Spring no injection of
When using the Spring framework, if the injection object instance fails, then the object is null
.
public class BeanExample {
@Autowired private BeanProvider beanProvider; public void run() { this.beanProvider.sayHello(this.name, this.age); } }
When the improper operation because
beanProvider
there is no injection, the callsayHello()
resulting in NPE time approaches.
The value of ConcurrentHashMap and Hashtable
Some do not support the null
collection of value added null
value elements, such as ConcurrentHashMap
and Hashtable
.
ConcurrentHashMap<String, String> map = new ConcurrentHashMap();
map.put("a", null);
Hashtable<String, String> hashtable = newHashtable<>();
hashtable.put("a", null);
These underlying collection
put(K key,V value)
method,key
orvalue
for thenull
case where the result NPE.
Second, how to prevent the null pointer exception
Since it is difficult to avoid NPE, we have to find ways to solve. Both have good coding habits, but also to the careful control of the business.
1. Normal processing
NPE carried out for the common defense against business method calls, you can simply add a non-empty judgment.
People people = new People();
People user = people.getUser("name");
if (user != null) {
String name = user.getName();
System.out.println(name);
}
2. When defining the object initialization
Define objects in their own time, pay attention to the initialization value for the Can null
.
// String str = "";
// 初始化为空字符串People people = newPeople();
// 初始化为对象
People user = people.getUser("name");
3. Use equals () method note
Known non-null object caller, such as constant values, as a caller enumeration value, avoiding the use of the object to invoke the method unknown, which can effectively prevent NPE.
String str = "123", string = null;
System.out.println(str.equals(string));
4. Use valueOf () instead of toString () method
Using the toString()
method to use to call the object methods, and the object is not clear whether in null
the case, that throws NPE. Using the valueOf()
method avoids the use of unknown objects to invoke methods to avoid.
People people = null;
System.out.println(String.valueOf(people)); // print:null
System.out.println(people.toString()); // NPE
5. The method of determining non-empty open source library
Recommended major open source library of StringUtils
string and CollectionUtils
a set of tools such as non-empty judgment.
String str = null;
List<String> list = null;
if (!StringUtils.isEmpty(str)) {
System.out.println(str);
}
if (!CollectionUtils.isEmpty(list)) {
System.out.println(list);
}
The method returns an empty set or a null array
In the process returns empty array and an empty rather than returning null
, JDK own Collections
set of tools provides several empty set of definitions.
public People[] getUsersArr() {
return new People[]{};
}
public List<People> getUsers() { // return Collections.emptyMap(); // return Collections.emptySet(); return Collections.emptyList(); }
7. Define whether the database field is empty
In some particular field may be determined according to whether the service is empty, and provided a reasonable default value. For example: represents the state of the business field.
CREATE TABLE user{ ... status NOT NULL DEFAULT 0 ...}
8. Optional use of Class JDK1.8
Providing preventing NPE particular container, it will be mentioned later after JDK1.8.
Three, Optional
Optional
It may comprise a null
or a non- null
container object. According to the source code analysis features:
Method 1. Definitions
1.1 empty
Returns an empty Optaional
instance, there are no values in this example.
public static<T> Optional<T> empty() { @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; }
1.2 of
A return value can not empty Optional
instance, is in this example null
when thrown NPE.
public static <T> Optional<T> of(T value) { return new Optional<>(value); } private Optional(T value) { this.value = Objects.requireNonNull(value); }
1.3 ofNullable
May return a null value Optional
example, the value in this example null
returns an empty time Optaional
instance.
public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); }
2. Functional Method
2.1 isPresent
If there is value exists, returns true
, otherwise it returns false
.
People people = new People();
System.out.println(Optional.ofNullable(people).isPresent());// print: true
people = null;
System.out.println(Optional.ofNullable(people).isPresent());// print: false
2.2 get()
If there is value exists, the return value, otherwise throw NoSuchElementException
.
People people = new People();
System.out.println(Optional.ofNullable(people).get());// print: People@61bbe9ba
people = null;
System.out.println(Optional.ofNullable(people).get());// print: Exception in thread "main" java.util.NoSuchElementException: No value present
Do not use this method to get the object.
2.3 orelse
If there exists a value, the return value, otherwise the orElse
method parameters may be used to define a default value.
String str = null;
String result = Optional.ofNullable(str).orElse("default");//print:default
System.out.println(result);
2.4 orElseGet
If there is value exists, the return value, otherwise the provider function, the function can return values to define default values.
String str = null;
String result = Optional.ofNullable(str).orElseGet(() -> "ajn");//print:ajn
System.out.println(result);
2.5 orElseThrow
If there is value exists, the return value, otherwise abnormal function interface parameter.
String str = null;
String result = Optional.ofNullable(str).orElseThrow(IllegalArgumentException::new);// print: Exception in thread "main" java.lang.IllegalArgumentException
System.out.println(result);
More details about the function interface, focusing on Java Functional Programming
2.6 ifPresent
If there is value exists, the function interface method parameters provided will be processed, otherwise does nothing.
Optional.ofNullable(getPeople()).ifPresent(people -> {
System.out.println("the people is nut null: " + people);
});
The above code is equivalent to:
People people = getPeople();
if (people != null) {
System.out.println("the people is nut null: " + people);
}
2.7 filter
If there exists a value, and the value in line with the conditions given function returns the current Optional
, otherwise an empty Optaional
instance, can be used to filter the special value.
String name = "AiJiangnan";// 给定的条件是字符串包含Ai
String result = Optional.of(name).filter(str -> str.contains("Ai")).orElse("字符串不包含Ai");
System.out.println(result);
2.8 map
If there exists a value, type value can be converted into the other type, and converts the return type of Optional
example, otherwise an empty Optaional
instance, it can be judged chain empty, very practical.
People people = null;
String result = Optional.ofNullable(people)
.map(People::getName)
.map(String::toUpperCase)
.orElse("default");
System.out.println(result);
Only when the
people
object is notnull
, andpeople.getName()
is notnull
, only to return name to all uppercase string, otherwise returns default.
2.9 flatMap
If there exists a value, type value can be converted into the other type, but can only turn to Optional
examples, otherwise an empty Optaional
instance. The method and map
method similar, but the method returns Optional
instance returned by the function parameters.
People people = new People();
people.setName(" ajn ");
String result = Optional.ofNullable(people)
.flatMap(peo -> Optional.ofNullable(peo.getName()))
.flatMap(str -> Optional.of(str.toUpperCase()))
.orElse("default");
System.out.println(result);