Java Null Pointer Exception

Null Pointer Exception(NPE)是 Java 语言中非常常见的一个问题。


Article.java

public class Article
{
    private Author author;

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }
}

Author.java

public class Author
{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Main.java

public class Main
{
    public static void main(String[] args) {
        Article article = null;

        System.out.println(article.getAuthor().getName());
    }
}

比如我们写了上面这样一段代码,运行时就会报 NullPointerException。

Exception in thread "main" java.lang.NullPointerException
        at Main.main(Main.java:6)

当然解决 NullPointerException 的方法也有很多,比如使用 if-else。

public class Main1
{
    public static void main(String[] args) {
        Article article = null;

        if (article != null && article.getAuthor() != null) {
            System.out.println(article.getAuthor().getName());
        } else {
            System.out.println("Unknown");
        }
    }
}

比如使用 Java 8 的 Optional。

import java.util.Optional;

public class Main2
{
    public static void main(String[] args) {
        Article article = null;

        System.out.println(Optional.ofNullable(article).map(Article::getAuthor).map(Author::getName).orElse("Unknown"));
    }
}

或者使用 Kotlin 的 Safe Calls。

data class Article(var author: Author?);

data class Author(var name: String);

fun findArticle() : Article? {return null}

fun main() {
    val article = findArticle();
    println(article?.author?.name)
}

参考:

https://blog.udemy.com/java-null-pointer-exception/

https://kotlinlang.org/docs/reference/null-safety.html

207 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *