温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java.lang.ClassCastException的java类型转换异常怎么解决

发布时间:2020-10-30 23:43:55 来源:亿速云 阅读:229 作者:Leah 栏目:开发技术

本篇文章为大家展示了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实现了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类型转换异常怎么解决,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI