如何运行JavaCompiler编译的代码?

tzi*_*zim 4 java jsr199 java-compiler-api

有没有办法运行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", " "));
    }
Run Code Online (Sandbox Code Playgroud)

现在我想用寿命1秒运行该程序并获得输出到字符串变量.有什么办法可以吗?

Pas*_*ent 5

你需要使用反射,类似的东西:

// 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);
Run Code Online (Sandbox Code Playgroud)

适应它当然是为了满足您的需求