解決java.lang.ClassCastException的java類型轉換異常的問題
在項目中,需要使用XStream將xml string轉成相應的對象,卻報出了java.lang.ClassCastException: com.model.test cannot be cast to com.model.test的錯誤。
原因:
項目中應該是采用了熱部署,devtools,因為累加載器的不同所以會導致類型轉換失敗
措施:
在pom.xml中將以下代碼注釋掉:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency>
補充知識:TreeSet在add對象時報ClassCastException錯誤
TreeSet實現(xiàn)了SortedSet接口,可以對集合中的對象進行排序,但是在使用TreeSet時要注意一點,那就是要給TreeSet傳遞一個比較器,也就是指定比較規(guī)則,否則的話,它就不知道誰大誰小,也就不能排序了。此時它會報一個ClassCastException的異常。
jdk1.6文檔里add方法關于這個異常是這樣描述的:
Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in this set
翻譯:ClassCastException - 如果指定的對象不能與當前在此集合中的元素進行比較
public class TreeSetTest{ public static void main(String[] args) { MyComparator comparator = new MyComparator(); // TreeSet<Student> set = new TreeSet<Student>(comparator); // 錯誤的代碼,少了比較器,運行則報下面的異常。 TreeSet<Student> set = new TreeSet<Student>(); Student s1 = new Student(50); Student s2 = new Student(70); Student s3 = new Student(40); set.add(s1); set.add(s2); set.add(s3); System.out.println(set); }}class Student { int score; public Student(int score) { this.score = score; } @Override public String toString() { // TODO Auto-generated method stub return String.valueOf(this.score); }}class MyComparator implements Comparator<Student>{ @Override //按分數(shù)高低比較,int為返回負數(shù)、零、整數(shù),這里我寫的不咋好,但意思一樣 public int compare(Student o1, Student o2) { // TODO Auto-generated method stub int result = 0; if(o1.score > o2.score) { result = 1; }else { result = -1; } return result; }}
錯誤的運行結果:
Exception in thread 'main' java.lang.ClassCastException: com.shengsiyuan2.Student cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1294) at java.util.TreeMap.put(TreeMap.java:538) at java.util.TreeSet.add(TreeSet.java:255) at com.shengsiyuan2.TreeSetTest.main(TreeSetTest.java:17)
解決辦法:
把 TreeSet set = new TreeSet(); 改成:TreeSet set = new TreeSet(comparator);即可。
以上這篇解決java.lang.ClassCastException的java類型轉換異常的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. 如何基于Python Matplotlib實現(xiàn)網格動畫2. 利用promise及參數(shù)解構封裝ajax請求的方法3. ASP 信息提示函數(shù)并作返回或者轉向4. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明5. ThinkPHP5實現(xiàn)JWT Token認證的過程(親測可用)6. Ajax實現(xiàn)表格中信息不刷新頁面進行更新數(shù)據(jù)7. JSP數(shù)據(jù)交互實現(xiàn)過程解析8. windows服務器使用IIS時thinkphp搜索中文無效問題9. .NET中l(wèi)ambda表達式合并問題及解決方法10. PHP設計模式中工廠模式深入詳解
