how to share objects between different classloaders?

前端 未结 3 1588
陌清茗
陌清茗 2021-01-01 19:03

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

相关标签:
3条回答
  • 2021-01-01 19:20

    Objects from different classloaders can interact with each other through interfaces and classes loaded by a common classloader.

    0 讨论(0)
  • 2021-01-01 19:21

    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.

    1. Using the Common Class Loader

    2. Sharing Libraries Across a Cluster

    3. Packaging the Client JAR for One Application in Another Application

    Refer to this link for more details.

    0 讨论(0)
  • 2021-01-01 19:31

    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.

    0 讨论(0)
提交回复
热议问题