how to share objects between different classloaders?

泄露秘密 提交于 2019-12-18 18:54:40

问题


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 deal with this?. Thanks


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7617990/how-to-share-objects-between-different-classloaders

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!