How to unload an already loaded class in Java? [duplicate]

落花浮王杯 提交于 2019-11-27 20:40:14

Java rebel reloads changed classes on the fly. See the jrebel website for details. I don't know that I would recommend this for a production environment though, because of performance issues. JRebel on occasion bogs things down momentarily when you've recompiled for a server.

You can't unload a class that is actually in use. But you might want to have a look at platforms like OSGi, if you want to reload or redeploy your application during runtime.

You can't explicitly unload a class.

In principle, you can expicitly reload a class via Classloader.loadClass(). From that moment onwards, all new instances of that class will use the new definition.

In any case, I would proceed with extreme caution...

You would have to create a custom ClassLoader: which returns all Objects wrapped inside a Proxy. The ClassLoader must have a list of all referenced Proxies (keep this list WeakReferenced). If you decide to "unload" and thus "reload" any class, you wait untill the class is loaded, find all Proxy's in your list, and replace the actual object.

There are several problems: you need Reflection, to get all private variables and reset the internal state (see setAccesible on Field). Also multi-threading problems might occour, thus the Proxy must be synchronized: which makes it performing poor.

You can better look for Google's Guice dependency solution, which enables unplugging and reloading modules at runtime. This might be a solution, but way too bloated for a small app. Still: I'm not sure wheter the GC also unloads unused classes.

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