Home > Java > javaTutorial > body text

How to avoid NullPointerException in Java

黄舟
Release: 2017-09-07 10:31:11
Original
1677 people have browsed it

This article mainly introduces the relevant information on the summary of methods to avoid NullPointerException (null pointer) in java. Friends in need can refer to the summary of

java. The summary of methods to avoid NullPointerException (null pointer)

Null pointer exceptions thrown in Java applications are the best way to resolve null pointers and are also the key to writing robust programs that work smoothly. As the saying goes, "Prevention is better than cure", this sentence is also true for such an annoying Null Pointer Exception. Thankfully, by applying some defensive coding techniques and tracking the connections between multiple parts of your application, you can control null pointer exceptions in Java to a good level. BTW, this is the second NullPointerException post on Javarevisited. In the previous post we discussed the common causes of null pointer exceptions in Java, and in this tutorial we will learn some Java programming tips and best practices. These tips can help you avoid null pointer exceptions in Java. Following these tips can also reduce the number of non-null checks present throughout your Java code. As an experienced Java programmer, you probably already know some of these techniques and apply them in your projects. But for novice and intermediate developers, it will be well worth learning. By the way, if you know any other Java tricks to avoid null pointer exceptions and reduce null pointer checks, please share them with us.

These are simple techniques that are easy to apply, but have a significant impact on code quality and robustness. In my experience, only the first tip significantly improves code quality. As I said before, if you know any Java tricks to avoid null pointer exceptions and reduce null pointer checks, you can share it by commenting on this article.

1) Call the equals() and equalsIgnoreCase() methods from a known String object, not an unknown object.

Always call the equals() method from a known non-empty String object. Because the equals() method is symmetrical, calling a.equals(b) and calling b.equals(a) are exactly the same, which is why programmers are so careless about objects a and b. If the caller is a null pointer, this call may result in a Null Pointer Exception


Object unknownObject = null;

//错误方式 – 可能导致 NullPointerException
if(unknownObject.equals("knownObject")){
  System.err.println("This may result in NullPointerException if unknownObject is null");
}

//正确方式 - 即便 unknownObject是null也能避免NullPointerException
if("knownObject".equals(unknownObject)){
  System.err.println("better coding avoided NullPointerException");
}
Copy after login

This is the simplest Java trick to avoid Null Pointer Exceptions, but can lead to huge improvements , because equals() is a common method.

2) When valueOf() and toString() return the same result, prefer to use the former.

Because calling toString() of a null object will throw a null pointer exception, if we can use valueOf() to obtain the same value, we would rather use valueOf() and pass a null to valueOf() Will return "null", especially in those wrapper classes like Integer, Float, Double and BigDecimal.


BigDecimal bd = getPrice();
System.out.println(String.valueOf(bd)); //不会抛出空指针异常
System.out.println(bd.toString()); //抛出 "Exception in thread "main" java.lang.NullPointerException"
Copy after login

3) Use null-safe methods and libraries There are many open source libraries that already do the heavy lifting of null pointer checking for you. One of the most commonly used is StringUtils in Apache commons. You can use StringUtils.isBlank(), isNumeric(), isWhiteSpace(), and other utility methods without worrying about null pointer exceptions.


//StringUtils方法是空指针安全的,他们不会抛出空指针异常
System.out.println(StringUtils.isEmpty(null));
System.out.println(StringUtils.isBlank(null));
System.out.println(StringUtils.isNumeric(null));
System.out.println(StringUtils.isAllUpperCase(null));

Output:
true
true
false
false
Copy after login

But don’t forget to read the documentation of the class for the null pointer method before making any conclusions. This is another Java best practice that can be greatly improved without a lot of effort.

4) Avoid returning a null pointer from a method, instead return an empty collection or empty array.

This Java best practice or trick is mentioned by Joshua Bloch in his book Effective Java. This is another tip to get better at programming in Java. By returning an empty collection or array, you can ensure that calls like size() and length() will not crash due to a Null Pointer Exception. The Collections class provides convenient empty Lists, Sets and Maps: Collections.EMPTY_LIST, Collections.EMPTY_SET, Collections.EMPTY_MAP. Here are examples.


public List getOrders(Customer customer){
  List result = Collections.EMPTY_LIST;
  return result;
}
Copy after login

You can also use Collections.EMPTY_SET and Collections.EMPTY_MAP instead of the null pointer.

5) Using annotation@NotNull and @Nullable

you can define whether it can be Null pointer. Declare whether a method is null pointer safe by using annotations like @NotNull and @Nullable. Modern compilers, IDEs, or tools can read this annotation and help you add null pointer checks that you forgot about, or prompt you with unnecessary null pointer checks. IntelliJ and findbugs already support these annotations. These annotations are also part of JSR 305, but even if they are not in the IDE or tool, the annotation itself can be used as documentation. Seeing @NotNull and @Nullable, the programmer can decide whether to do null pointer checking. By the way, this technique is relatively new to Java programmers and will take a while to adopt.

6) Avoid unnecessary automatic wrapping and automatic unwrapping in your code.

Regardless of other shortcomings such as creating temporary objects, if the wrapper class object is null, automatic wrapping can also easily cause a null pointer exception. For example, if the person object does not have a phone number, null will be returned, and the following code will crash due to a null pointer exception.


Person ram = new Person("ram");
int phone = ram.getPhone();
Copy after login

当使用自动包装和自动解包的时候,不仅仅是等号,< > 同样会抛出空指针异常。你可以通过这篇文章来学习更多的Java中的自动包装和拆包的陷阱。

7) 遵从Contract并定义合理的默认值。

在Java中避免空指针异常的一个最好的方法是简单的定义contract并遵从它们。大部分空指针异常的出现是因为使用不完整的信息创建对象或者未提供所有的依赖项。如果你不允许创建不完整的对象并优雅地拒绝这些请求,你可以在接下来的工作者预防大量的空指针异常。类似的,如果对象允许创建,你需要给他们定义一个合理的默认值。例如一个Employee对象不能在创建的时候没有id和name,但是是否有电话号码是可选的。现在如果Employee没有电话号码,你可以返回一个默认值(例如0)来代替返回null。但是必须谨慎选择,哟有时候检查空指针比调用无效号码要方便。同样的,通过定义什么可以是null,什么不能为null,调用者可以作出明智的决定。failing fast或接受null同样是一个你需要进行选择并贯彻的,重要的设计决策

8)定义数据库中的字段是否可为空。

如果你在使用数据库来保存你的域名对象,如Customers,Orders 等,你需要在数据库本身定义是否为空的约束。因为数据库会从很多代码中获取数据,数据库中有是否为空的检查可以确保你的数据健全。在数据空中维护null约束同样可以帮助你减少Java代码中的空指针检查。当从数据库中加载一个对象是你会明确,哪些字段是可以为null的,而哪些不能,这可以使你代码中不必要的!= null检查最少化。

9) 使用空对象模式(Null Object Pattern)

还有一种方法来避免Java中的空指针异常。如果一个方法返回对象,在调用者中执行一些操作,例如Collection.iterator()方法返回迭代器,其调用者执行遍历。假设如果一个调用者并没有任何迭代器,其可以返回空对象(Null object)而非null。空对象是一个特殊的对象,其在不同的上下文中有不同的意义。例如一个空的迭代器调用hasNext()返回false时,可以是一个空对象。同样的在返回Container和Collection类型方法的例子中,空对象可以被用来代替null作为返回值。我打算另写一篇文章来讲空对象模式,分享几个Java空对象的例子。

这就是全部了,这是几个易于遵从的避免空指针异常的Java技巧和最佳实践。你可以欣赏到这些技巧将非常有用,且不太难实现。如果你有其他比秒这个异常的技巧,而又没包含在这里,请通过评论来和我们分享,我将收录在这里。

The above is the detailed content of How to avoid NullPointerException in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template