转换回原始类时出现ClassCastException错误 [英] ClassCastException error when casting back to original class

查看:131
本文介绍了转换回原始类时出现ClassCastException错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public void doJob() {
    MyObj s;

    for ( Object o : MyObj.all().fetch()) {
        s = (MyObj) o;  // ClassCastException here

        if (!s.fileExists()) {
        //Do some stuff
        }
    }
}

抛出此异常:

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

(此方法在Play Job类中运行,如果这很重要。)

(This method runs inside a Play Job class, if that matters.)

MyObj.all()。fetch()返回包含数据库中所有 MyObj 对象的某种Iterable 。 MyObj 从Play继承此方法! Framework的Model类,如果重要的话。这就是为什么它返回对象而不是 MyObj 的列表,我无法改变它的工作原理。

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 Objects rather than MyObjs, and I can't change how it works.

那么,有什么理由让我无法转回 MyObj ?我可以看到如何从 Object 中抛出一些奇怪的东西,但Java似乎知道该对象的类曾经是什么。

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.

谢谢!

推荐答案

看起来你有ClassLoader问题。 fetch()方法返回的对象被加载到与当前线程中用于尝试和转换的不同的ClassLoader中。

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
    }
}

这篇关于转换回原始类时出现ClassCastException错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆