Solution for the ClassCastException due to ClassLoader issue

后端 未结 5 584
既然无缘
既然无缘 2020-12-03 19:06

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.

5条回答
  •  忘掉有多难
    2020-12-03 19:30

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

    • One solution would be to create a "common" class-loader which loads the classes to be used by your custom classloaders. So in your case, you'd have a new classloader which would load the given class and your custom classloaders would extend this classloader.
    • Another solution would be to pass around the "serialized" state between the two classloaders. Serialize one instance to a byte array and reconstruct the object in the other classloader by de-serializing the object stream.

提交回复
热议问题