Can a java classloader load a class more than once, ie load new versions of a class, without throwing a LinkageError of "duplicate class definition"?
In other words, if we need to dynamically reload a class, can this be done with the same classloader, or does the classloader have to be destroyed first and a new one be created that will load the new version of the class?
A classloader can only actually load a class once! That means that it can only define it once. It can load it many times, but only the first time it will define it. The rest of the times it will load the existing instance it has already defined from the first time.
Trying to define a class twice causes a
LinkageError
of "duplicate class definition". If there is a need for classes to be loaded and reloaded many times then this must be done by different classloaders like this:Of course, this causes an extra load, but if you need it that is OK.
Also, be careful to not leave any references of your classes lying around when destroying the old instance of your classloader, as this will cause a memory leak!
The reason to reload the class is changes in class. In this space hot spot cares about reloading of the class automatically. So you do not have to care about this. I hope this helps.