Java中java.lang.ClassCastException異常原因及解決方法
通常我們在 OOP 設計中都會使用到繼承。
??但是在繼承對象之間的強制轉換可能會遇到??java.lang.ClassCastException?
?異常的錯誤。
錯誤的日志如下:
19:58:25.010 [http-nio-8080-exec-5] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: class com.ossez.usreio.mls.common.models.response.ListingResponse cannot be cast to class com.ossez.usreio.mls.common.models.response.ListingDetailResponse (com.ossez.usreio.mls.common.models.response.ListingResponse and com.ossez.usreio.mls.common.models.response.ListingDetailResponse are in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @4ee285c6)] with root cause java.lang.ClassCastException: class com.ossez.usreio.mls.common.models.response.ListingResponse cannot be cast to class com.ossez.usreio.mls.common.models.response.ListingDetailResponse (com.ossez.usreio.mls.common.models.response.ListingResponse and com.ossez.usreio.mls.common.models.response.ListingDetailResponse are in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @4ee285c6)
??問題和原因
這個問題出現(xiàn)的原因就是繼承類之間強制轉換的錯誤。
同時這個錯誤是運行時錯誤,不是編譯錯誤,因此你編譯的時候是沒有這個錯誤的。
考察下面的代碼:
Parent b = new parent(); Child c = (Child) b ;
采用該方法不能實現(xiàn)對象類型由超類向子類的轉換。
上面的原因是父類的對象是由父類創(chuàng)建的,然后你嘗試將父類創(chuàng)建的對象強制轉換到子類中。
因為父類創(chuàng)建的對象和子類需要創(chuàng)建的對象分別使用不同的地址空間,那在轉換的時候將會出現(xiàn)地址空間引用的錯誤,因此 JVM 會認為你將 2 個完全不同類型的對象進行轉換,這個時候出現(xiàn)上面的運行時錯誤。
要解決這個問題的辦法就是在創(chuàng)建父類的時候使用子類來創(chuàng)建,并且強制將創(chuàng)建的父類轉換為子類就可以了。
使用這種創(chuàng)建方法就能保證使用相同的地址空間。
將上面的語句改成:
Parent b = new Child (); Child c = (Child) b ;
就可以了。
總結
到此這篇關于Java中java.lang.ClassCastException異常原因及解決方法的文章就介紹到這了,更多相關java.lang.ClassCastException異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot安全認證Security的實現(xiàn)方法
這篇文章主要介紹了SpringBoot安全認證Security的實現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05SpringCloud使用Feign實現(xiàn)遠程調用流程詳細介紹
OpenFeign源于Netflix的Feign,是http通信的客戶端。屏蔽了網(wǎng)絡通信的細節(jié),直接面向接口的方式開發(fā),讓開發(fā)者感知不到網(wǎng)絡通信細節(jié)。所有遠程調用,都像調用本地方法一樣完成2023-02-02Spring?Security中如何獲取AuthenticationManager對象
有時需要使用AuthenticationManager(以下簡稱Manager)對象,可是這個對象不是Bean,沒有直接保存在Spring的Bean庫中,那么如何獲取Spring Security中的這個對象呢,需要的朋友可以參考下2022-11-11Spring使用IOC與DI實現(xiàn)完全注解開發(fā)
IOC也是Spring的核心之一了,之前學的時候是采用xml配置文件的方式去實現(xiàn)的,后來其中也多少穿插了幾個注解,但是沒有說完全采用注解實現(xiàn)。那么這篇文章就和大家分享一下,全部采用注解來實現(xiàn)IOC + DI2022-09-09