Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

java - Solution for the ClassCastException due to ClassLoader issue

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.

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.

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() 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...