Java中在runner类调用Book类toString方法及空指针问题解决
Book类toString调用与空指针异常排查
初始需求
学习Java过程中,借助Eclipse自带的「生成toString()」功能完成了Book类的toString方法重写,希望可以在独立的runner类中正确调用该方法输出图书详情。
已编写的相关代码
Book类实现
import java.time.LocalDateTime; import com.library.entity.Publication; public class Book extends Publication { public Book(String title, String firstName, String lastName, String publisherName, String address, LocalDateTime datePublished) { super(title, firstName, lastName, publisherName, address, datePublished); } @Override public String toString() { return "Book [getTitle()=" + getTitle() + ", getDatePublished()=" + getDatePublished() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
尝试调用方法的runner类实现
package com.library.runner; import java.time.LocalDateTime; import com.library.entity.publication.*; public class BookstoreRunner{ public static void main(String args[]) { Book book1 = new Book("Generic Title", "K", "L", "K Publishing", "Earth", LocalDateTime.now()); String bookdetails = book1.toString(); System.out.println(bookdetails); } }
父类Publication实现
package com.library.entity; import java.time.LocalDateTime; public class Publication { private String title; private Author author; private Publisher publisher; private LocalDateTime datePublished; public Publication(String title, String firstName, String lastName, String publisherName, String address, LocalDateTime datePublished) { this.title = title; author.setFirstName(firstName); author.setLastName(lastName); publisher.setPublisherName(publisherName); publisher.setAddress(address); this.datePublished = datePublished; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public LocalDateTime getDatePublished() { return datePublished; } public void setDatePublished(LocalDateTime datePublished) { this.datePublished = datePublished; } }
运行时异常
执行runner类的main方法时,控制台抛出空指针异常,完整堆栈信息如下:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.library.entity.Author.setFirstName(String)" because "this.author" is null at com.library.entity.Publication.<init>(Publication.java:14) at com.library.entity.publication.Book.<init>(Book.java:12) at com.library.runner.BookstoreRunner.main(BookstoreRunner.java:9)
问题排查与解决
报错的核心原因是Java中引用类型成员变量的默认值为null,和toString的调用方式没有关系。
- 原Publication类中仅声明了
Author author、Publisher publisher两个引用类型字段,没有完成对象实例化:
此时两个字段的默认值为null,在类的构造方法中直接执行private Author author; private Publisher publisher;author.setFirstName(firstName)这类方法调用时,因为操作的是null对象,就会触发空指针异常。从堆栈信息可以看到,异常是在执行父类构造方法、创建Book对象的阶段就抛出的,代码根本还没运行到调用toString()的那一行。 - 修正空指针问题的方式:在字段声明阶段就完成对象实例化:
private final Author author = new Author(); private final Publisher publisher = new Publisher(); - 原本编写的toString调用逻辑本身没有问题:修正上述构造方法的空指针问题后,既可以按照原有写法显式调用
book1.toString()拿到图书详情字符串,也可以直接在打印语句中传入Book对象,由JVM自动调用重写后的toString方法输出内容,不需要额外调整调用逻辑。
内容的提问来源于stack exchange,提问作者kajl16
相关产品推荐
相关产品推荐

