The null pointer exception class Optional Optional class with a null pointer exception

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 nullthrows a null pointer exception ( NullPointerExceptionabbreviated the NPE ). Include the following:

  • Call an nullobject instance method
  • Access to or modification of nullthe object's field
  • To obtain an array of nulllength when
  • Access or modification to the array nullindex value of
  • Throw an Throwableobject nullexception 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 nullcase, 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 returns null, the object's direct call back method causes NPE.

2. Automatic packaging value unboxed

In the packaging object is nullthe case, the automatic unpacking operation.

Integer a = null;
int b = a;// System.out.println(1 == a);

In the above example the packaging class object ainitialization value is defined null, in the aassignment of basic data types to btime, and the basic data types 1when equality of logic operations are carried out automatically unpacking operation, aas nullwhen the result NPE.

3. iterating over collections and arrays empty object

In the collection or array is unclear whether the nulltime, 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 nullcaused 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 beanProviderthere is no injection, the call sayHello()resulting in NPE time approaches.

The value of ConcurrentHashMap and Hashtable

Some do not support the nullcollection of value added nullvalue elements, such as ConcurrentHashMapand 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, keyor valuefor the nullcase 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 nullthe 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 StringUtilsstring and CollectionUtilsa 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 Collectionsset 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

OptionalIt may comprise a nullor a non- nullcontainer object. According to the source code analysis features:

Method 1. Definitions

1.1 empty

Returns an empty Optaionalinstance, 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 Optionalinstance, is in this example nullwhen 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 Optionalexample, the value in this example nullreturns an empty time Optaionalinstance.

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 Optaionalinstance, 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 Optionalexample, otherwise an empty Optaionalinstance, 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 peopleobject is not null, and people.getName()is not null, 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 Optaionalinstance. The method and mapmethod similar, but the method returns Optionalinstance 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);
 
Tags:  the Java

First, what is the null pointer exception

When the program needs to return object instance nullthrows a null pointer exception ( NullPointerExceptionabbreviated the NPE ). Include the following:

  • Call an nullobject instance method
  • Access to or modification of nullthe object's field
  • To obtain an array of nulllength when
  • Access or modification to the array nullindex value of
  • Throw an Throwableobject nullexception 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 nullcase, 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 returns null, the object's direct call back method causes NPE.

2. Automatic packaging value unboxed

In the packaging object is nullthe case, the automatic unpacking operation.

Integer a = null;
int b = a;// System.out.println(1 == a);

In the above example the packaging class object ainitialization value is defined null, in the aassignment of basic data types to btime, and the basic data types 1when equality of logic operations are carried out automatically unpacking operation, aas nullwhen the result NPE.

3. iterating over collections and arrays empty object

In the collection or array is unclear whether the nulltime, 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 nullcaused 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 beanProviderthere is no injection, the call sayHello()resulting in NPE time approaches.

The value of ConcurrentHashMap and Hashtable

Some do not support the nullcollection of value added nullvalue elements, such as ConcurrentHashMapand 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, keyor valuefor the nullcase 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 nullthe 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 StringUtilsstring and CollectionUtilsa 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 Collectionsset 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

OptionalIt may comprise a nullor a non- nullcontainer object. According to the source code analysis features:

Method 1. Definitions

1.1 empty

Returns an empty Optaionalinstance, 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 Optionalinstance, is in this example nullwhen 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 Optionalexample, the value in this example nullreturns an empty time Optaionalinstance.

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 Optaionalinstance, 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 Optionalexample, otherwise an empty Optaionalinstance, 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 peopleobject is not null, and people.getName()is not null, 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 Optaionalinstance. The method and mapmethod similar, but the method returns Optionalinstance 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);

Guess you like

Origin www.cnblogs.com/xichji/p/12105433.html