使用javax.tools.JavaCompiler在内存中完全编译代码

2022-09-01 00:54:29

我正在使用javax.tools包(JDK 1.7)中的JavaCompiler来动态编译一些东西,如下所示:

compiler.run(null, null, "-cp", paths, "path/to/my/file.java");

它可以工作,但我想在内存中完成所有操作(例如,使用代码传递字符串,而不是源文件,并获取字节码而不是.class文件)。我发现扩展和参数是没有用的,因为它可能与控制台中的参数相同。您知道使 run 方法像这样工作的方法吗?或者您知道使用该方法执行此操作的已确认方法吗?(扩展FileManager看起来很容易,但并不是那么容易:)InputStreamOutputStreamgetTask()


答案 1

我已经在Mac OS Java 7中运行了上述代码。它们都不起作用。所以我写了一 https://github.com/trung/InMemoryJavaCompiler

StringBuilder source = new StringBuilder()
    .append("package org.mdkt;\n")
    .append("public class HelloClass {\n")
    .append("   public String hello() { return \"hello\"; }")
    .append("}");

Class<?> helloClass = InMemoryJavaCompiler.compile("org.mdkt.HelloClass", source.toString());

答案 2

我认为这里可能会有所帮助,它基本上显示了如何从内存编译Java源代码(字符串位于类中)。

它使用 and 将源代码写入内存中的 /,然后使用该类(从 JDK 6 开始)编译并运行该程序:PrinterWriterStringWriterStringJavaCompiler

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;


public class CompileSourceInMemory {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    out.println("public class HelloWorld {");
    out.println("  public static void main(String args[]) {");
    out.println("    System.out.println(\"This is in another java file\");");    
    out.println("  }");
    out.println("}");
    out.close();
    JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);

    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
      System.out.println(diagnostic.getCode());
      System.out.println(diagnostic.getKind());
      System.out.println(diagnostic.getPosition());
      System.out.println(diagnostic.getStartPosition());
      System.out.println(diagnostic.getEndPosition());
      System.out.println(diagnostic.getSource());
      System.out.println(diagnostic.getMessage(null));

    }
    System.out.println("Success: " + success);

    if (success) {
      try {

          URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
          Class.forName("HelloWorld", true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });

      } catch (ClassNotFoundException e) {
        System.err.println("Class not found: " + e);
      } catch (NoSuchMethodException e) {
        System.err.println("No such method: " + e);
      } catch (IllegalAccessException e) {
        System.err.println("Illegal access: " + e);
      } catch (InvocationTargetException e) {
        System.err.println("Invocation target: " + e);
      }
    }
  }
}

class JavaSourceFromString extends SimpleJavaFileObject {
  final String code;

  JavaSourceFromString(String name, String code) {
    super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
    this.code = code;
  }

  @Override
  public CharSequence getCharContent(boolean ignoreEncodingErrors) {
    return code;
  }
}

如果您查看参考链接,您还会发现更多其他示例

参考:


推荐