Created
September 1, 2016 22:17
-
-
Save edefazio/3b84ad5dcd2113cbde9a19715916e913 to your computer and use it in GitHub Desktop.
varcode metaprogramming using CodeML (generating .java code and running at runtime)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ex.varcode.codeml; | |
import varcode.java.Java; | |
/*{$$condenseBlankLines$$}*/ | |
/*{-*/import varcode.java.JavaCase;/*-}*/ | |
public class /*{+className*/CodeMLHelloWorld/*+}*/ { | |
public static void main( String[] args ) { | |
System.out.println( "{+message+}" ); | |
} | |
/*{-*/ | |
/**<PRE> | |
* *1* find and read the .java source for this class | |
* *2* "tailor" a new (.java) file with binding the key-value values | |
* *3* print out the tailored (.java) | |
* *4* (javac) compiles the tailored (.java) to a tailored (.class) | |
* *5* load the tailored (.class) into a ClassLoader | |
* *6* invoke the main method on the tailored (.class) | |
*/ | |
public static class Tailor { | |
public static void main( String[] args ) { | |
JavaCase helloCase = | |
JavaCase.of( // *1* | |
CodeMLHelloWorld.class, // *1* | |
"ex.varcode.codeml.HelloWorld", // *2* | |
"message", "Hello CodeML!" ); // *2* | |
System.out.println( helloCase ); // *3* | |
Class<?> clazz = helloCase.loadClass(); // *4* *5* | |
Java.invokeStatic( // *6* | |
clazz, "main", (Object)new String[ 0 ] ); | |
} | |
} | |
/*-}*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Metaprogramming Java (HelloWorld) Examples:
*IMPORTANT NOTE: all examples REQUIRE a Runtime JDK (not a JRE) to compile
Java Code (.java files) to .class files at runtime. (and varcode) *
varcode JavaModel
varcode CodeML
varcode BindML
JavaPoet / varcode
varcode (and in particular varcode JavaModel) makes metaprogramming easy by composing Java source files in a way that is natural and intuitive.
varcode is easy to write, use, test, modify and maintain (it looks just like the Java code you already know.)
Alternatively JavaPoet is clunky, because:
it requires manual code to call the Java Compiler.
generated code "does", therefore it's harder to learn, use, test, and maintain.
Having the ability to easily invoke the Javac compiler with a simple method makes iteration and testing MUCH easier with varcode)