[英]ClassCastException error when casting back to original class
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.) (如果重要,此方法在Play Job类中运行。)
The MyObj.all().fetch()
is returning an Iterable of some kind containing all of the MyObj
objects in the database. MyObj.all().fetch()
返回一个包含数据库中所有MyObj
对象的Iterable。 MyObj
inherits this method from the Play! MyObj
从Play继承了这个方法! Framework's Model class, if that matters. Framework的Model类,如果重要的话。 That's why it's returning a list of
Object
s rather than MyObj
s, and I can't change how it works. 这就是为什么它返回一个
Object
而不是MyObj
的列表,我无法改变它的工作原理。
So, is there some reason that I can't cast back to MyObj
? 那么,有什么理由让我无法回到
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. 我可以看到如何从一个
Object
抛出一些古怪的东西,但Java似乎知道对象的类曾经是什么。
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. 我在StackOverflow上看到了一篇最近的帖子,表明如果同一个类的两个相同的实例被不同的类加载器加载,则不能在它们之间进行转换。
Check whether you are not subject to the multiple classloader condition here too. 检查您是否也不受此多个类加载器条件的限制。
It looks like you have ClassLoader issues. 看起来你有ClassLoader问题。 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.
fetch()方法返回的对象被加载到与当前线程中用于尝试和转换的不同的ClassLoader中。
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. 在循环中使用
o.getClass().getName()
来知道什么是.all().fetch()
真正返回。
Note : Maybe some model.Survey
objects? 注意 :也许是一些
model.Survey
对象?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.