java.lang.ClassCastException: sametype cannot be cast to sametype

≡放荡痞女 提交于 2019-12-08 12:18:59

问题


very strange exception

my code

 Query q = em.createQuery("SELECT  u FROM Chatuser u");

            List<Chatuser> list = (List<Chatuser>) q.getResultList();
            for (int i = 0; i < list.size(); i++) {
                Object aa = list.get(i);
                Chatuser chatuser = (Chatuser)aa;

exception

   ex = (java.lang.ClassCastException) java.lang.ClassCastException: Entities.service.Chatuser cannot be cast to Entities.service.Chatuser

what is the problem ?


回答1:


This post probably answers also your question
Java, getting class cast exception where both classes are exactly the same

There could be problem with conflicting Classloaders




回答2:


please try the following :

Query q = em.createQuery("SELECT  u FROM Chatuser u", Chatuser.class);

List<Chatuser> list = q.getResultList();

for (Chatuser chatuser : list) {
    ....
    chatuser.doSomething();
    ...
}

If you set the target Class on the createQuery Method already, you can avoid the downcast. If its not working, please past more infos, (Chatuser.java) JPA(Hibernate) Version, etc)

Cheers Jens




回答3:


it is because the generics

List<Chatuser> list = 

use this form

for(ChatUser u : list) {
u.doSomething();
}


来源:https://stackoverflow.com/questions/17231535/java-lang-classcastexception-sametype-cannot-be-cast-to-sametype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!