I need different classloaders to be able to unload classes. But i need to share objects between them (actually i am getting ClassCastException). So what are the solutions to
Objects from different classloaders can interact with each other through interfaces and classes loaded by a common classloader.
One of the primary objectives of using separate classloaders is to prevent exactly the kind of thing that you are trying to do. Security and name conflicts are good reasons for keeping this isolation. Here are a few ways that you can circumvent this isolation.
Using the Common Class Loader
Sharing Libraries Across a Cluster
Packaging the Client JAR for One Application in Another Application
Refer to this link for more details.
Will also mention that if you are using interfaces, you can use java.lang.reflect.Proxy to create an instance of an interface local to your classloader which, under the hood, makes calls with reflection to the "real" (foreign) object from a different classloader. It's ugly, and if parameters or return types are not primitive, you will just be passing the ClassCastException further down the line. While you can rig something up to make this work, in general, it is better to either have a parent classloader with some shared types that you want to be able to use across classloaders, or use a more... serialized format for communication (slower), or only share interfaces that deal in primitives.