我正在用java构建一个可以接收java源文件的服务器,它应该使用JavaCompiler动态编译它,然后加载该类。然而问题是,如果服务器接收到一个同名但内容不同的文件,它仍然会加载以前的类并给出相同的输出。我注意到一些答案建议为我尝试加载的类创建一个超类并使用不同的类加载器,但是如果 java 源文件被动态发送到服务器,情况仍然如此吗?
这是我在 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();
}
}