15

I want to create a new ClassLoader everytime my method is called.

So I can reload a class without exiting my program.

A way how I can update a class loaded by ClassLoader would also be a solution.

How can I achieve that?

Arian
  • 3,183
  • 5
  • 30
  • 58
  • I load a JavaCompiler sourcecode compiled class with loadClass("string"), then I run this class with JUnitCore. After that I edit the source code in the *.java, compile it with the JavaCompiler and want to reload it again. – Arian Mar 22 '12 at 09:32
  • 1
    Interesting question for a good use case. +1 – Andrew Thompson Mar 22 '12 at 09:53

2 Answers2

11

I found a good explained answer here:

http://www.exampledepot.com/egs/java.lang/reloadclass.html

The important thing is to have two binary folders, in my case: one for the testcases and one for the program source.

Quote:

URL[] urls = null;
try {
    // Convert the file object to a URL
    File dir = new File(System.getProperty("user.dir")
        +File.separator+"dir"+File.separator);
    URL url = dir.toURL();        // file:/c:/almanac1.4/examples/
    urls = new URL[]{url};
} catch (MalformedURLException e) {
}

try {
    // Create a new class loader with the directory
    ClassLoader cl = new URLClassLoader(urls);

    // Load in the class
    Class cls = cl.loadClass("MyReloadableClassImpl");
Arian
  • 3,183
  • 5
  • 30
  • 58
  • Just to add - this solution works only if your reloaded class doesn't have any method deletion/new class reference. The problem with this approach is that if someone fogets to add dependent classes first, this might create NoClassDefFoundError. The best thing is to reload all classes without fully stoppping the application. – ha9u63a7 Jan 10 '18 at 10:18
  • Link in answer is dead. – Glen Apr 10 '19 at 15:29
6

saw this ? ClassLoader Load / Reload Example

I think this blog can satisfy your requirement.

liam xu
  • 2,892
  • 10
  • 42
  • 65