Skip to content

Instantly share code, notes, and snippets.

@edefazio
Created September 1, 2016 22:17
Show Gist options
  • Save edefazio/3b84ad5dcd2113cbde9a19715916e913 to your computer and use it in GitHub Desktop.
Save edefazio/3b84ad5dcd2113cbde9a19715916e913 to your computer and use it in GitHub Desktop.
varcode metaprogramming using CodeML (generating .java code and running at runtime)
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 ] );
}
}
/*-}*/
}
@edefazio
Copy link
Author

edefazio commented Sep 1, 2016

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:

  • JavaPoet was designed purely as a code generation engine (not as a way to build AND compile Java code)
    it requires manual code to call the Java Compiler.
  • JavaPoet API is fluent and uses the builder pattern, but (unfortunately) doesn't do a good job explaining what the
    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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment