有没有办法运行通过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秒该程序,并获得输出到字符串变量。有什么办法,我可以做到这一点?

有帮助吗?

解决方案

您需要使用反射,这样的事情:

// 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);

适应课程,以满足您的需求。

其他提示

您必须编译的类添加到当前类路径。

有许多方法可以做到这一点,取决于你的项目是如何设置的。下面是一个实例使用java.net.URLClassLoader的:

ClassLoader cl_old = Thread.currentThread().getContextClassLoader();
ClassLoader cl_new = new URLClassLoader(urls.toArray(new URL[0]), cl_old);

其中“网址”是指向文件系统的URL的列表。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top