Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ClassLoader: load same class twice

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?

like image 295
arket Avatar asked Oct 19 '25 09:10

arket


2 Answers

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!

like image 128
Andreas Dolk Avatar answered Oct 21 '25 21:10

Andreas Dolk


You have to load a new ClassLoader each time, or you have to give the class a different name each time and access it via an interface.

e.g.

interface MyWorker {
  public void work();
}

class Worker1 implement MyWorker {
  public void work() { /* code */ }
}

class Worker2 implement MyWorker {
  public void work() { /* different code */ }
}
like image 26
Peter Lawrey Avatar answered Oct 21 '25 21:10

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!