I currently have this code:
private void compile(){
List<File> files = getListOfJavaFiles();
//JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
//compiler.run(null, null, null, srcDirectory.getPath()+"/Main.java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(files);
List<String> optionList = new ArrayList<String>();
// set compiler's classpath to be same as the runtime's
optionList.addAll(Arrays.asList("-classpath",System.getProperty("java.class.path")));
//need to add options here.
compiler.getTask(null, fileManager, null, optionList, null, compilationUnits1).call();
//compiler.run(null, null, null, srcDirectory.getPath()+"/Main.java");
// fileManager.close();
}
But I am stuck now trying to make this actually run the files which have been compiled.
I see no output from this in the console, however in the Main.java file which I have compiled successfully (I can see the .class files), I have put “System.out.println(“Main class is running”);, so I would expect to see this when I run the application.
You can create an URLClassLoader to load your newly compiled classes, or you can have a look at a library I wrote which will compile in memory and load into the current class loader by default.
http://vanillajava.blogspot.co.uk/2010/11/more-uses-for-dynamic-code-in-java.html
If you have generated code, it will save the file to a source directory when debugging so you can step into the generated code (otherwise it does everything in memory)
You can only load a class once this way so if you need to load many versions I suggest you implement an interface and change the name of the class each time.