问题
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