This question already has an answer here:
I want to treat a String as a Java file then compile and run it. In other words, use Java as a script language.
To get better performance, we should avoid writing .class
files to disk.
This question already has an answer here:
I want to treat a String as a Java file then compile and run it. In other words, use Java as a script language.
To get better performance, we should avoid writing .class
files to disk.
This answer is from one of my blogs, Compile and Run Java Source Code in Memory.
Here are the three source code files.
MemoryJavaCompiler.java
MemoryJavaFileManager.java
MemoryClassLoader.java
Explanations:
StringInputBuffer
class in theMemoryJavaFileManager.java
..class
files in memory, I implemented a classMemoryJavaFileManager
. The main idea is to override the functiongetJavaFileForOutput()
to store bytecodes into a map.MemoryClassLoader
, which reads bytecodes in the map and turn them into classes.Here is a unite test.
Reference