Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save edefazio/9aa8961da4b5d6d5dd750e29d54cc05e to your computer and use it in GitHub Desktop.
Save edefazio/9aa8961da4b5d6d5dd750e29d54cc05e to your computer and use it in GitHub Desktop.
varcode metaprogramming with the JavaModel Api (generating .java code and running at runtime)
package ex.varcode.java.model;
import varcode.java.Java;
import varcode.java.JavaCase;
import varcode.java.model._class;
/**<PRE>
* *1* build a _class model
* *2* print out the model (.java) source
* *3* (javac) compile the (.java) source to a .class
* *4* load the .class in a ClassLoader
* *5* invoke the main method on the loaded .class</PRE>
*/
public class JavaModelHelloWorld
{
public static void main(String[] args)
{
JavaCase helloCase =
new _class(
"ex.varcode.javamodel",
"public final class HelloModel" )
.method(
"public static void main(String[] args)",
"System.out.println(\"Hello Java Model!\");" )
.toJavaCase( ); // *1*
System.out.println( helloCase ); // *2*
Class<?> helloClass = helloCase.loadClass(); // *3* *4*
Java.invokeStatic(
helloClass, "main", (Object)new String[ 0 ] ); // *5*
}
}
@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