I have the following code:
public void doJob() {
MyObj s;
for ( Object o : MyObj.all().fetch()) {
s = (MyObj) o; // ClassCastException here
if (!s.fileExists()) {
//Do some stuff
}
}
}
which is throwing this exception:
play.exceptions.JavaExecutionException: models.MyObj cannot be cast to models.MyObj
at play.jobs.Job.call(Job.java:155)
at Invocation.Job(Play!)
Caused by: java.lang.ClassCastException: models.MyObj cannot be cast to models.MyObj
at jobs.OrphanSurveys.doJob(OrphanSurveys.java:18)
at play.jobs.Job.doJobWithResult(Job.java:50)
at play.jobs.Job.call(Job.java:146)
... 1 more
(This method runs inside a Play Job class, if that matters.)
The MyObj.all().fetch()
is returning an Iterable of some kind containing all of the MyObj
objects in the database. MyObj
inherits this method from the Play! Framework's Model class, if that matters. That's why it's returning a list of Object
s rather than MyObj
s, and I can't change how it works.
So, is there some reason that I can't cast back to MyObj
? I can see how there would be some weirdness casting back from an Object
, but Java seems to know what the class of the object used to be.
Thanks!
I saw a recent post here on StackOverflow that indicated that if two otherwise identical instances of the same class are loaded by different classloaders, you cannot cast between them.
Check whether you are not subject to the multiple classloader condition here too.
It looks like you have ClassLoader issues. The objects being returned by your fetch() method were loaded in a different ClassLoader than the one being used in the current thread to try and cast.
Try this to confirm. Add the three lines of code to your exising code.
for ( Object o : MyObj.all().fetch()) {
// Check classloaders
System.out.println(o.getClass().getClassLoader());
System.out.println(MyObj.class.getClassLoader());
break;
//
s = (MyObj) o; // ClassCastException here
if (!s.fileExists()) {
//Do some stuff
}
}
From your stack trace, apparently, there's some other kinds of entries in your collection. Use o.getClass().getName()
inside your loop to know what is .all().fetch()
really returning.
Note : Maybe some model.Survey
objects?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.