Dynamically Reloading a Modified Class in Java

Description

The following code shows how to dynamically Reloading a Modified Class.

Example


//from  ww w .  j a v  a  2  s. c  o  m
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

class MyClass{
  public String myMethod() {
    return "a message";
  }
}

public class Main {
  public static void main(String[] argv) throws Exception {

    URL[] urls = null;

    File dir = new File(System.getProperty("user.dir") + File.separator + "dir" + File.separator);
    URL url = dir.toURI().toURL();
    urls = new URL[] { url };

    ClassLoader cl = new URLClassLoader(urls);

    Class cls = cl.loadClass("MyClass");

    MyClass myObj = (MyClass) cls.newInstance();
    
    System.out.println(myObj);

  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy