有没有办法运行JavaCompiler编译的程序?javax.tools.JavaCompiler
我的代码:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content));
task.call();
List<String> returnErrors = new ArrayList<String>();
String tmp = new String();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
tmp = String.valueOf(diagnostic.getLineNumber());
tmp += " msg: "+ diagnostic.getMessage(null);
returnErrors.add(tmp.replaceAll("\n", " "));
}现在我想运行生命周期为1秒的程序,并将输出输出到字符串变量。我有办法做到这一点吗?
发布于 2010-01-29 02:29:16
你需要使用反射,就像这样:
// Obtain a class loader for the compiled classes
ClassLoader cl = fileManager.getClassLoader(CLASS_OUTPUT);
// Load the compiled class
Class compiledClass = cl.loadClass(CLASS_NAME);
// Find the eval method
Method myMethod = compiledClass.getMethod("myMethod");
// Invoke it
return myMethod.invoke(null);当然,根据您的需要对其进行调整
发布于 2010-01-29 02:36:36
您必须将编译后的类添加到当前类路径中。
有许多方法可以做到这一点,这取决于您的项目是如何设置的。下面是一个使用java.net.URLClassLoader的实例:
ClassLoader cl_old = Thread.currentThread().getContextClassLoader();
ClassLoader cl_new = new URLClassLoader(urls.toArray(new URL[0]), cl_old);其中" urls“是指向文件系统的urls列表。
https://stackoverflow.com/questions/2156842
复制相似问题