|
| 1 | +//17 and up, originally by [email protected]. |
| 2 | + |
| 3 | +import javax.tools.*; |
| 4 | +import javax.tools.JavaFileObject.Kind; |
| 5 | +import java.net.URI; |
| 6 | +import java.util.*; |
| 7 | + |
| 8 | +public class InProcessCompileDemo { |
| 9 | + public static void main(String[] args) throws Exception { |
| 10 | + String jvmVersion="17"; |
| 11 | + if (args.length>0) { |
| 12 | + jvmVersion=args[0]; |
| 13 | + } |
| 14 | + String className = "Hello"; |
| 15 | + String sourceCode = """ |
| 16 | + public class Hello { |
| 17 | + public static void main(String[] args) { |
| 18 | + System.out.println("Hello from in-memory compiled code!"); |
| 19 | + } |
| 20 | + } |
| 21 | + """; |
| 22 | + |
| 23 | + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); |
| 24 | + if (compiler == null) { |
| 25 | + System.err.println("❌ No system compiler found — you're probably on a stripped JRE."); |
| 26 | + return; |
| 27 | + } |
| 28 | + System.out.println("✅ Compiler loaded: " + compiler.getClass().getName()); |
| 29 | + |
| 30 | + // in-memory source |
| 31 | + JavaFileObject source = new StringJavaFileObject(className, sourceCode); |
| 32 | + |
| 33 | + // file manager that captures class bytes in memory |
| 34 | + DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); |
| 35 | + StandardJavaFileManager std = compiler.getStandardFileManager(diagnostics, null, null); |
| 36 | + MemoryFileManager memFM = new MemoryFileManager(std); |
| 37 | + |
| 38 | + // compile for a specific release (22 here) |
| 39 | + JavaCompiler.CompilationTask task = compiler.getTask( |
| 40 | + null, memFM, diagnostics, |
| 41 | + List.of("--release", jvmVersion), null, List.of(source)); |
| 42 | + |
| 43 | + boolean ok = task.call(); |
| 44 | + diagnostics.getDiagnostics().forEach(System.out::println); |
| 45 | + |
| 46 | + if (!ok) { |
| 47 | + System.out.println("❌ Compilation failed"); |
| 48 | + return; |
| 49 | + } |
| 50 | + System.out.println("✅ Compilation succeeded"); |
| 51 | + |
| 52 | + // load and run main() |
| 53 | + ClassLoader loader = new MemoryClassLoader(memFM.getClassBytes()); |
| 54 | + Class<?> hello = loader.loadClass(className); |
| 55 | + hello.getMethod("main", String[].class).invoke(null, (Object) new String[0]); |
| 56 | + } |
| 57 | + |
| 58 | + // ===== Helpers ===== |
| 59 | + |
| 60 | + // Source stored entirely in memory |
| 61 | + static final class StringJavaFileObject extends SimpleJavaFileObject { |
| 62 | + private final String code; |
| 63 | + StringJavaFileObject(String className, String code) { |
| 64 | + super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); |
| 65 | + this.code = code; |
| 66 | + } |
| 67 | + @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } |
| 68 | + } |
| 69 | + |
| 70 | + // Captures compiled class bytes in memory |
| 71 | + static final class MemoryFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> { |
| 72 | + private final Map<String, ByteArrayJavaFileObject> classFiles = new HashMap<>(); |
| 73 | + MemoryFileManager(StandardJavaFileManager fileManager) { super(fileManager); } |
| 74 | + @Override |
| 75 | + public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) { |
| 76 | + ByteArrayJavaFileObject file = new ByteArrayJavaFileObject(className, kind); |
| 77 | + classFiles.put(className, file); |
| 78 | + return file; |
| 79 | + } |
| 80 | + Map<String, byte[]> getClassBytes() { |
| 81 | + Map<String, byte[]> out = new HashMap<>(); |
| 82 | + for (var e : classFiles.entrySet()) out.put(e.getKey(), e.getValue().getBytes()); |
| 83 | + return out; |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + // Holds class bytes |
| 88 | + static final class ByteArrayJavaFileObject extends SimpleJavaFileObject { |
| 89 | + private final java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); |
| 90 | + ByteArrayJavaFileObject(String name, Kind kind) { |
| 91 | + super(URI.create("mem:///" + name.replace('.', '/') + kind.extension), kind); |
| 92 | + } |
| 93 | + @Override public java.io.OutputStream openOutputStream() { return out; } |
| 94 | + byte[] getBytes() { return out.toByteArray(); } |
| 95 | + } |
| 96 | + |
| 97 | + // ClassLoader that defines classes from captured bytes |
| 98 | + static final class MemoryClassLoader extends ClassLoader { |
| 99 | + private final Map<String, byte[]> classes; |
| 100 | + MemoryClassLoader(Map<String, byte[]> classes) { |
| 101 | + super(InProcessCompileDemo.class.getClassLoader()); |
| 102 | + this.classes = classes; |
| 103 | + } |
| 104 | + @Override |
| 105 | + protected Class<?> findClass(String name) throws ClassNotFoundException { |
| 106 | + byte[] bytes = classes.get(name); |
| 107 | + if (bytes == null) throw new ClassNotFoundException(name); |
| 108 | + return defineClass(name, bytes, 0, bytes.length); |
| 109 | + } |
| 110 | + } |
| 111 | +} |
0 commit comments