Is it possible to somehow “import” a new Java class into a running program and use it?
Can a program create a new file of the type ".java" and then include it in the project files and reference it without restarting the program?
Below is an example of what I mean:
import java.io.*; public class Program { File JClass = new File("JClass.java"); public static BufferedWriter out = null; public static void main(String[] args) { try { out = new BufferedWriter(new FileWriter("JClass.java")); out.write("public abstract class JClass {"); out.newLine(); out.newLine(); out.write(" public void printSomething(String a) {"); out.newLine(); out.write(" System.out.println(a);"); out.newLine(); out.write(" }"); out.newLine(); out.write("}"); out.close(); } catch (IOException e) { System.exit(-1); }
The resulting JClass.java file:
public abstract class JClass { public void printSomething(String a) { System.out.println(a); } }
Similarly, is it possible to create a copy of one of the source files of the project, edit the code in the file and then somehow force the changes in the current program?
At the moment, I do not care about the practical application. I just study different ideas related to programming. I also understand that this is a potential for all kinds of disasters. Editing executable code and including classes on the fly (which, I believe, will not be checked for errors, because other classes are used when building a project) can have very unpredictable results. I just want to talk to this idea.
However, if anyone has USEFUL warnings or things to look for, I would appreciate it. Otherwise, I would be grateful if people did not respond to this: "This is a bad idea" or "there are simpler and more effective ways to solve problems." I am NOT trying to solve the problem with this. I am only studying this idea.
So is this possible?
Jonathan
source share