I am working on an IDE like project where code changed by user gets recompiled by JavaCompiler at runtime and needs to be reloaded to execute the changed code, I am using reflection to do that, but the problem is the class once loaded by ClassLoader never gets changed on re executing the code below it remains static, but when I exit the complete application and restart it then i can see the changes in recompiled code. Below is my code which I am using:
Class<?> clazz = Class.forName("Projects.Demo."+classname);
Constructor<?> ctor = clazz.getConstructor(App.class, Ctrl.class);
Object object = ctor.newInstance(new Object[] { app , ctrl});
One of the solution I found is on java2s.com which is titled as "Dynamically Reloading a Modified Class":
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();
}
but its not working for me as the changed class never gets reloaded by this code.
Please help me or suggest me if any other option is available to do this.