Search code examples
javaclassloadclassloaderreload

Can a java classloader load a class more than once


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?


Solution

  • 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:

    Create a classloader of your own that will load your classes. When you want to reload any class you must destroy your classloader and then create a new instance of it that will load the new versions of your classes.

    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!