Java ClassLoader: load same class twice

Tags: , ,



I have a ClassLoader which loads a class compiled by JavaCompiler from a source file. But when I change the source file, save it and recompile it, the ClassLoader still loads the first version of the class.

   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   Class<?> compiledClass = cl.loadClass(stringClass);

What am I missing? like a newInstance or something?

Answer

A classloader can’t replace a class that already has been loaded. loadClass will return the reference of the existing Class instance.

You’ll have to instantiate a new classloader and use it to load the new class. And then, if you want to “replace” the class, you’ll have to throw this classloader away and create another new one.


In response to your comment(s): do something like

ClassLoader cl = new UrlClassLoader(new URL[]{pathToClassAsUrl});
Class<?> compiledClass = cl.loadClass(stringClass);

This classloader will use the “default delegation parent ClassLoader” and you have to take care, the class (identified by it fully qualified classname) has not been loaded and can’t be loaded by that parent classloader. So the “pathToClassAsUrl” shouldn’t be on the classpath!



Source: stackoverflow