Methods to avoid NULL pointer exceptions in Java _java

Source: Internet
Author: User
Tags stack trace static class wrapper

No one likes null pointer exceptions! Is there any way to avoid them? Well, maybe.

This article will discuss the following technologies

1.Optional type (newly introduced in Java 8)
2.Objects Class (Java 7 Central)

The optional class in Java 8

What is it?

New types introduced in 1.Java 8
2. It is a wrapper for a specified type of object or for a scenario where the object (NULL) does not exist

In short, it is a better alternative to handling null values (warning: At first glance may not be so obvious)

Basic usage

It's a type (a class)--so, how do you create an instance of this type?

You can use the three static methods below it:

Copy Code code as follows:

public static optional<string> stringoptional (String input) {
return optional.of (input);
}

Simple and straightforward-create a optional wrapper that contains this value. Remember--If this value is null, it throws npe!

Copy Code code as follows:

public static optional<string> stringnullableoptional (String input) {
if (!new Random (). Nextboolean ()) {
input = null;
}
return optional.ofnullable (input);
}

Personally, I think it's a little better. There is no risk of NPE-if you enter null, an empty optional is returned.

Copy Code code as follows:

public static optional<string> emptyoptional () {
return Optional.empty ();
}

If you really just want to return a "null" value. The null value does not imply null.

Well, how do you spend/use optional?

Copy Code code as follows:

public static void Consumingoptional () {
Optional<string> wrapped = optional.of ("astring");
if (Wrapped.ispresent ()) {
System.out.println ("Got string-" + wrapped.get ());
}
else {
SYSTEM.OUT.PRINTLN ("Gotcha!");
}
}

The easy way to do this is to check if the optional wrapper really has a value (using the Ispresent method)-You'll wonder what the benefits are compared to using if (myobj!= null). Don't worry, I'll make myself clear on that.

Copy Code code as follows:

public static void Consumingnullableoptional () {
String input = null;
if (new Random (). Nextboolean ()) {
input = "Icanbenull";
}
Optional<string> wrapped = optional.ofnullable (input);
System.out.println (Wrapped.orelse ("Default"));
}

You can use the OrElse method so that you can use it to return a default value in case the package is really a null value-its benefits are obvious. You can avoid the obvious redundant way of invoking the Ifpresent method when you extract the real value.

Copy Code code as follows:

public static void Consumingemptyoptional () {
String input = null;
if (new Random (). Nextboolean ()) {
input = "Icanbenull";
}
Optional<string> wrapped = optional.ofnullable (input);
System.out.println (Wrapped.orelseget (
()-> {
return "Defaultbysupplier";
}

));
}

I'm a little confused about that. Why are there two different methods for the same purpose? OrElse and Orelseget can be overloaded (with the same name but with different parameters).

Either way, the obvious difference between the two methods is their arguments-you can choose to do this (a functional interface) using a lambda expression rather than an instance of supplier.

Why is using optional more powerful than a common null check?

1. The biggest advantage of using optional is that you can articulate your intentions more clearly--the return of a null value will make the consumer wonder (when it really happens NPE) This is not intentional return, so you have to look at Javadoc to further position. And the use of optional is quite clear.

2. With optional you can completely avoid NPE-as mentioned above, using Optional.ofnullable,orelse and orelseget can keep us away from NPE.

Another Savior!

Look at this code fragment.

Copy Code code as follows:

Package com.abhirockzz.wordpress.npesaviors;

Import Java.util.Map;
Import java.util.Objects;

public class Usingobjects {

String Getval (map<string, string> AMap, string key) {
return Amap.containskey (key)? Amap.get (key): null;
}

public static void Main (string[] args) {
Usingobjects obj = new usingobjects ();
Obj.getval (NULL, "dummy");
}
}

Which one is likely to be empty?

1.Map objects
2. Search for the use of key
3. This instance of the method call

If we throw NPE, how can we be sure which one is null?

Copy Code code as follows:

Package com.abhirockzz.wordpress.npesaviors;

Import Java.util.Map;
Import java.util.Objects;

public class Usingobjects {
String Getvalsafe (map<string, string> AMap, string key) {
map<string, string> safemap = Objects.requirenonnull (AMap,
"Map is null");
String Safekey = Objects.requirenonnull (Key, "key is null");

Return Safemap.containskey (Safekey)? Safemap.get (Safekey): null;
}

public static void Main (string[] args) {
Usingobjects obj = new usingobjects ();
Obj.getvalsafe (NULL, "dummy");
}
}

Requirenonnull method

1. Returns the object if it is not null
2. If the value is NULL, the returned NPE will have the specified message

Why is it better than if (Myobj!=null)?

The stack trace information you see will clearly see the Objects.requirenonnull method call. This, together with your own error log, allows you to locate the problem more quickly ... At least it seems to me to be quicker.

You can also customize the validator, such as implementing a simple validator to ensure that there are no null values.

Copy Code code as follows:

Import java.util.Collections;
Import java.util.List;
Import java.util.Objects;
Import Java.util.function.Predicate;

public class Randomgist {

public static <T> T Requirenonempty (t object, predicate<t> predicate, String Msgtocaller) {
Objects.requirenonnull (object);
Objects.requirenonnull (predicate);
if (Predicate.test (object)) {
throw new IllegalArgumentException (Msgtocaller);
}
return object;
}

public static void Main (string[] args) {

Usage 1:an empty string (intentional)

String s = "";
System.out.println (Requirenonempty (Objects.requirenonnull (s), (S1)-> s1.isempty (), "My String is empty!"));

Usage 2:an Empty List (intentional)
List List = Collections.emptylist ();
System.out.println (Requirenonempty (Objects.requirenonnull (list), (L)-> l.isempty (), "list is empty!"). Size ());

Usage 3:an Empty User (intentional)
User user = New User ("");
System.out.println (Requirenonempty (objects.requirenonnull (user), (u)-> u.getname (). IsEmpty (), "User is empty!"));
}

private Static Class User {
private String name;

Public User (String name) {
THIS.name = name;
}

Public String GetName () {
return name;
}
}
}

Don't let NPE be miserable in the wrong place. We have many tools to better handle NPE and even eradicate them completely!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.