I'm building a server in java that can receive java source files, and it should dynamically compile it using JavaCompiler and then load the class. However the problem is that if the server receive a file with the same name but different content, it will still load the previous class and gave the same outputs. I've noticed some answers suggesting creating a superclass for the class I'm trying to load and using a different classLoader, but is it still the case if the java source file is dynamically sent to the server?
Here's my compile and load methods in FileServer.java:
public final static int FILE_SIZE = 1022386;
public static void compile(String fileName)
{
// Save source in .java file.
File sourceFile = new File(fileName);
// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector <JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager =
compiler.getStandardFileManager(diagnostics, null, null);
File [] files = new File [] {sourceFile};
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files));
String [] compileOptions = new String[] {"-classpath", "runtime.jar"};
Iterable<String> compilationOptions = Arrays.asList(compileOptions);
JavaCompiler.CompilationTask task =
compiler.getTask(null, fileManager, diagnostics, compilationOptions,
null, compilationUnits);
task.call();
}
public static void compileLoad (String fileName)
{
compile(fileName);
String className = "";
int i = 0;
while(fileName.charAt(i) != '.') {
className += fileName.charAt(i);
i++;
}
ClassLoader classLoader = FileServer.class.getClassLoader();
// Dynamically load class and invoke its main method.
try {
//Class<?> cls = Class.forName(className);
Class<?> cls = classLoader.loadClass(className);
Method meth = cls.getMethod("main", String[].class);
String[] params = null;
meth.invoke(null, (Object) params);
} catch (Exception e) {
e.printStackTrace();
}
}