Java StackOverflowError詳解
StackOverflowError
原因 : 函數(shù)調(diào)用棧太深了,注意代碼中是否有了循環(huán)調(diào)用方法而無(wú)法退出的情況
原理
StackOverflowError 是一個(gè)java中常出現(xiàn)的錯(cuò)誤:在jvm運(yùn)行時(shí)的數(shù)據(jù)區(qū)域中有一個(gè)java虛擬機(jī)棧,當(dāng)執(zhí)行java方法時(shí)會(huì)進(jìn)行壓棧彈棧的操作。在棧中會(huì)保存局部變量,操作數(shù)棧,方法出口等等。jvm規(guī)定了棧的最大深度,當(dāng)執(zhí)行時(shí)棧的深度大于了規(guī)定的深度,就會(huì)拋出StackOverflowError錯(cuò)誤。
典型的例子:
public class StackOverFlowDemo { public static void Foo(){ Foo(); } public static void main(String[] args) { Foo(); } }
今天我遇見了另外一種情況:當(dāng)兩個(gè)對(duì)象相互引用,在調(diào)用toString方法時(shí)會(huì)產(chǎn)生這個(gè)異常,因?yàn)樗鼈儠?huì)循環(huán)調(diào)用toString方法。
//book和student相互循環(huán)引用 public class StackOverFlowDemo { static class Student{ String name; Book book; public Student(String name) { this.name = name; } //循環(huán)調(diào)用toString方法 @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", book=" + book + '}'; } } static class Book { String isbn; Student student; public Book(String isbn, Student student) { this.isbn = isbn; this.student = student; } @Override public String toString() { return "Book{" + "isbn='" + isbn + '\'' + ", student=" + student + '}'; } } public static void main(String[] args) { Student student=new Student("zhang3"); Book book=new Book("1111",student); student.book=book; System.out.println(book.toString()); } }
出現(xiàn)的錯(cuò)誤:
toString()
說到toString()方法,在打印一個(gè)對(duì)象時(shí),會(huì)先調(diào)用這個(gè)對(duì)象的toString()方法,例如:
public class toStringDemo { static class A{ @Override public String toString() { System.out.print("I "); return ""; } } public static void main(String[] args) { A a=new A(); System.out.println("love you."+a); } }
會(huì)輸出:
I love you.
到此這篇關(guān)于Java StackOverflowError詳解的文章就介紹到這了,更多相關(guān)Java StackOverflowError內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot整合日志處理Logback的實(shí)現(xiàn)示例
Logback是由log4j創(chuàng)始人設(shè)計(jì)的又一個(gè)開源日志組件,本文主要介紹了springboot整合日志處理Logback,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01Guava自動(dòng)加載緩存LoadingCache使用實(shí)戰(zhàn)詳解
這篇文章主要為大家介紹了Guava自動(dòng)加載緩存LoadingCache使用實(shí)戰(zhàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12mybatis-plus的SafetyEncryptProcessor安全加密處理示例解析
這篇文章主要為大家介紹了mybatis-plus的SafetyEncryptProcessor安全加密處理示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08SpringBoot事件機(jī)制相關(guān)知識(shí)點(diǎn)匯總
這篇文章主要介紹了SpringBoot事件機(jī)制相關(guān)知識(shí)點(diǎn)匯總,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Solr通過特殊字符分詞實(shí)現(xiàn)自定義分詞器詳解
最近因?yàn)楣ぷ鞯男枰鲆粋€(gè)分詞器,通過查找相關(guān)的資料最終用solr實(shí)現(xiàn)了,下面這篇文章主要給大家介紹了關(guān)于Solr通過特殊字符分詞實(shí)現(xiàn)自定義分詞器的相關(guān)資料,需要的朋友可以參考借鑒,下面隨著小編來一起看看吧。2017-09-09