package pmbauer; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; public class JavaIsKindaLight { public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { StringBuilder sb = new StringBuilder(); sb.append("package test;"); sb.append("import java.util.*;"); sb.append("public class ParseSomeCode { "); sb.append(" public static Object data() {"); sb.append(" Map m = new HashMap() {{"); sb.append(" put(\"parse\", new HashMap() {{"); sb.append(" put(\"some\", \"data\");"); sb.append(" }});"); sb.append(" }};"); sb.append(" return ((Map)((Map)m.get(\"parse\"))).get(\"some\");"); sb.append(" }"); sb.append("}"); // Save source in .java file. File root = new File("/tmp"); File sourceFile = new File(root, "test/ParseSomeCode.java"); sourceFile.getParentFile().mkdirs(); Files.write(sourceFile.toPath(), sb.toString().getBytes(StandardCharsets.UTF_8)); // compile JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); compiler.run(null, null, null, sourceFile.getPath()); // load, run URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); Class cls = Class.forName("test.ParseSomeCode", true, classLoader); Method method = cls.getMethod("data"); System.out.println(method.invoke(null)); } }