Yes, there are two solutions, but they take soem explaining.
The first is that Hostpot 1.5 contains a new API to switch method code on the fly. Ive never sued it so can’t tell you much about it ewxcept its ONLY for repalcing the code of a method with other code-- you cannot add or remove methods nor can you chnage fields.
However there is an older technique called class unloading that lets you do all of that. The way it works is this:
A Class is a just an object like any other object in Java. If there are no references to that class, it can get garbage collected and then the next time that class is refernced it will be reloaded.
However, once a class is laoded by a ClassLoader , the class loader keeps a reference to that class. Therefor in order for their to be no rererences to the class, there first have to be no refernces to the ClassLoader that loaded it.
All instances of classes keep a reference to the class loader that loaded the calss their are an instacne of. So all of thsoe instance objects have to go de-referenced first.
THEREFOR to truly unload a class, you need to delete all the instacnes of ALL the calsses that were laoded by the class loader that laoded that class. It turns out in order to do this you need to use a custom class loader to load the classes you want unlaoed as the classpath class loader and the boot class loader by definition always have class instances that are “live” and refernced as long as the VM is running.
Additionally classes are relative to the class laoder theya re laoded by. Class “foo” loaded by class laoder A is a different class then class “foo” loaded by class laoder B. So in order to re-load a class, you need to create a new class loader and load the class through it, then use that class loader to create your instances.
If all you want to do is create a new object that is an instacen of the new version of the class then thats really all yo uhave to do. If however you want to “update” an objectand rpeserve its calues then you need to get fancier, Basically you need to store the valeusin some form that cnba then be laoded into the new instance of the object. The simpelst way is to serialize the obejct into memory and the de-serialize it using the new vclass laoder.
if al lthis seems abit complex, frnakly, it is. Class loaders are one of Java’s most powerful features but they arent for thsoe just trying to figure otu how to program basic code. Theya re an advanced feature that take even experienced programmers some tiem to really learn to use well.
Anyway I hope that helps some.