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 Object
s wrapped inside a Proxy. The ClassLoader
must have a list of all referenced Proxies (keep this list WeakReference
d). 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.
精彩评论