开发者

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

This question already has answers here: Unloading classes in java? (7 answers) Closed 6 years ago.

How to unload a class from the class loader, so that I can use the recently changed class on the fly without restarting my application (hot deployment)? Is it possible to do t开发者_如何学Pythonhat?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜