Class InMemoryJavaCompiler

java.lang.Object
org.elasticsearch.test.compiler.InMemoryJavaCompiler

public class InMemoryJavaCompiler extends Object
An in-memory java source code compiler. InMemoryJavaCompiler can be used for compiling source code, represented as a CharSequence, to byte code, represented as a byte[].

The compiler will not use the file system at all, instead using a ByteArrayOutputStream for storing the byte code.

Example:


     Map<String, CharSequence> sources = Map.of(
       "module-info",
       """
       module foo {
         exports p;
       }
       """,
       "p.Foo",
       """
       package p;
       public class Foo implements java.util.function.Supplier<String> {
        @Override public String get() {
          return "Hello World!";
         }
       }
       """
     );
     Map<String, byte[]> result = compile(sources);
 
  • Constructor Details

    • InMemoryJavaCompiler

      public InMemoryJavaCompiler()
  • Method Details

    • compile

      public static Map<String,byte[]> compile(Map<String,CharSequence> sources, String... options)
      Compiles the classes with the given names and source code.
      Parameters:
      sources - A map of class names to source code
      options - Additional command line options (optional)
      Returns:
      A Map containing the resulting byte code from the compilation, one entry per class name
      Throws:
      RuntimeException - If the compilation did not succeed
    • compile

      public static byte[] compile(String className, CharSequence sourceCode, String... options)
      Compiles the class with the given name and source code.
      Parameters:
      className - The name of the class
      sourceCode - The source code for the class with name className
      options - Additional command line options (optional)
      Returns:
      The resulting byte code from the compilation
      Throws:
      RuntimeException - If the compilation did not succeed