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

 更新时间:2020年9月28日 11:29  点击:2077

在项目中,需要使用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实现了SortedSet接口,可以对集合中的对象进行排序,但是在使用TreeSet时要注意一点,那就是要给TreeSet传递一个比较器,也就是指定比较规则,否则的话,它就不知道谁大谁小,也就不能排序了。此时它会报一个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
  //按分数高低比较,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;
  }
}

错误的运行结果:

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

[!--infotagslink--]

相关文章