Close

Java Compiler API - Compile and Load in Memory Dynamic Code

[Last Updated: Jul 3, 2017]

In the previous topics we saw how to compile java sources from string objects to files and load them using default or URLClassLoader. In this example we are going to show how to compile code to in memory byte stream instead of a file and load it from same byte array using a custom class loader. Here are the steps (some steps are overlapping from last two examples)

  1. To read code from a String source, create JavaStringObject extending SimpleJavaFileObject.
  2. To write compiled code to ByteArrayOutputStream, create class JavaByteObject extending SimpleJavaFileObject. We have to override openOutputStream() and return our stream to replace the default one.
  3. In order to hook up our JavaByteObject with the compiler, we need to extend StandardJavaFileManager. But there's no default implementation of that class in the standard API so we have to extend ForwardingJavaFileManager which delegates method calls to the underlying implementation. We have to override getJavaFileForOutput and return instance of our JavaByteObject.
  4. Last step: we have to create a custom class loader by extending ClassLoader. We will override findClass which will simply return the bytes retrieved from the in memory ByteArrayOutputStream.
  5. Run the main class StringCompilations.java.


Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.0.4

Java Compiler Memory Loader Example Select All Download
  • in-memory-compiler-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • StringCompilation.java

    See Also