解决java.lang.ClassCastException的java类型转换异常的问题

2025-05-29 0 78

在项目中,需要使用XStream将xml string转成相应的对象,却报出了java.lang.ClassCastException: com.model.test cannot be cast to com.model.test的错误。

原因:

项目中应该是采用了热部署,devtools,因为累加载器的不同所以会导致类型转换失败

措施:

在pom.xml中将以下代码注释掉:

?

1

2

3

4

5
<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<scope>runtime</scope>

</dependency>

补充知识:TreeSet在add对象时报ClassCastException错误

TreeSet实现了SortedSet接口,可以对集合中的对象进行排序,但是在使用TreeSet时要注意一点,那就是要给TreeSet传递一个比较器,也就是指定比较规则,否则的话,它就不知道谁大谁小,也就不能排序了。此时它会报一个ClassCastException的异常。

jdk1.6文档里add方法关于这个异常是这样描述的

Throws:

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

翻译:ClassCastException – 如果指定的对象不能与当前在此集合中的元素进行比较

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58
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

//按分数高低比较,int为返回负数、零、整数,这里我写的不咋好,但意思一样

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;

}

}

错误的运行结果:

?

1

2

3

4

5
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类型转换异常的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/mianyao1004/article/details/99738947

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 解决java.lang.ClassCastException的java类型转换异常的问题 https://www.kuaiidc.com/116350.html

相关文章

发表评论
暂无评论