Skip to content

Instantly share code, notes, and snippets.

@pmbauer
Last active February 2, 2017 21:45
Show Gist options
  • Save pmbauer/1a9be8e51264970b1fe1ed496f931d73 to your computer and use it in GitHub Desktop.
Save pmbauer/1a9be8e51264970b1fe1ed496f931d73 to your computer and use it in GitHub Desktop.
rough semantic equivalent in java to https://twitter.com/chrishouser/status/826884726485032960
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"); // On Windows running on C:\, this is C:\java.
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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment