Created
September 1, 2016 22:20
-
-
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)
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.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* | |
} | |
} |
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)