I am working on a project similar to the IDE, where user-modified code is recompiled by JavaCompiler at runtime and needs a reboot to execute the modified code. I use reflection for this, but the problem is that the class once loaded by ClassLoader never gets changed when the code below is repeated, it remains static, but when I exit the full application and restart it, I see the changes in the recompiled code. Below is my code that I use:
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 solutions I found is on java2s.com, which is called "Dynamic reloading of 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 it does not work for me, since the changed class is never reloaded with this code.
Please help me or suggest me if there is another option for this.
user1306589
source share