由于ClassLoader问题导致ClassCastException的解决方案 [英] Solution for the ClassCastException due to ClassLoader issue

查看:266
本文介绍了由于ClassLoader问题导致ClassCastException的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个加载相同类的ClassLoader。所以,显然这些不能相互投射。但是我需要访问在另一个ClassLoader中创建的对象。

I have two ClassLoaders which loads the same class. So, obviously these can't cast to one another. But I need to access an object created in the other ClassLoader.

我可以访问两个ClassLoader。如何在其他类中使用该对象?我不需要将对象转换为与当前ClassLoader匹配。

I have access to both ClassLoaders. How can I use that object in the other class? I don't need to cast the object to match to the current ClassLoader.

但问题是返回的对象的类型是 Object 。所以,我必须抛弃该对象来访问某些方法。我怎样才能做到这一点?像下面这样的正常转换导致ClassCastException,我已经知道了。

But the issue is that the returned object's type is Object. So, I have to cast down that object to access some methods. How can I do that? Normal cast like the following causes ClassCastException, which I already know.

Mojo mojo = (Mojo) descriptor.getMojo();

descriptor#getMojo()返回一个对象类型 Mojo 但该方法返回 Object 。怎么办呢?

descriptor#getMojo() returns an object of type Mojo but the method returns Object. How can do this?

如果您需要更多信息,请告诉我。

Let me know if you need further info.

我已经阅读了有关类加载的所有理论,但没有人为此指定了适当的解决方案。

I've read all the theories about classloading, but none has specified a proper solution for this.

推荐答案

AFAIK,不,你不能在另一个类加载器中转换由一个类加载器加载的类的对象。

AFAIK, no, you can't cast an object of a class loaded by one class-loader in another class loader.


  • 一种解决方案是创建一个通用类加载器,它加载要由自定义类加载器使用的类。因此,在您的情况下,您将有一个新的类加载器,它将加载给定的类,您的自定义类加载器将扩展此类加载器。

  • 另一种解决方案是传递序列化状态两个类加载器之间。将一个实例序列化为一个字节数组,并通过反序列化对象流来重构另一个类加载器中的对象。

这篇关于由于ClassLoader问题导致ClassCastException的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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