国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

解決java.lang.ClassCastException的java類(lèi)型轉(zhuǎn)換異常的問(wèn)題

瀏覽:5日期:2022-08-23 15:57:34

在項(xiàng)目中,需要使用XStream將xml string轉(zhuǎn)成相應(yīng)的對(duì)象,卻報(bào)出了java.lang.ClassCastException: com.model.test cannot be cast to com.model.test的錯(cuò)誤。

原因:

項(xiàng)目中應(yīng)該是采用了熱部署,devtools,因?yàn)槔奂虞d器的不同所以會(huì)導(dǎo)致類(lèi)型轉(zhuǎn)換失敗

措施:

在pom.xml中將以下代碼注釋掉:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency>

補(bǔ)充知識(shí):TreeSet在add對(duì)象時(shí)報(bào)ClassCastException錯(cuò)誤

TreeSet實(shí)現(xiàn)了SortedSet接口,可以對(duì)集合中的對(duì)象進(jìn)行排序,但是在使用TreeSet時(shí)要注意一點(diǎn),那就是要給TreeSet傳遞一個(gè)比較器,也就是指定比較規(guī)則,否則的話,它就不知道誰(shuí)大誰(shuí)小,也就不能排序了。此時(shí)它會(huì)報(bào)一個(gè)ClassCastException的異常。

jdk1.6文檔里add方法關(guān)于這個(gè)異常是這樣描述的

Throws:

ClassCastException - if the specified object cannot be compared with the elements currently in this set

翻譯:ClassCastException - 如果指定的對(duì)象不能與當(dāng)前在此集合中的元素進(jìn)行比較

public class TreeSetTest{ public static void main(String[] args) { MyComparator comparator = new MyComparator(); // TreeSet<Student> set = new TreeSet<Student>(comparator); // 錯(cuò)誤的代碼,少了比較器,運(yùn)行則報(bào)下面的異常。 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 //按分?jǐn)?shù)高低比較,int為返回負(fù)數(shù)、零、整數(shù),這里我寫(xiě)的不咋好,但意思一樣 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; }}

錯(cuò)誤的運(yùn)行結(jié)果:

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類(lèi)型轉(zhuǎn)換異常的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 富阳市| 牡丹江市| 定南县| 昔阳县| 日照市| 库尔勒市| 如东县| 天祝| 南靖县| 枣阳市| 光山县| 襄垣县| 温州市| 长沙市| 繁昌县| 宽甸| 基隆市| 卢湾区| 若羌县| 西青区| 沙坪坝区| 张家口市| 武威市| 浠水县| 北流市| 阳原县| 泽州县| 元谋县| 酒泉市| 吴忠市| 锦屏县| 九台市| 榆中县| 江都市| 新巴尔虎右旗| 嘉黎县| 汤原县| 会理县| 日喀则市| 上饶县| 登封市|