Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save edefazio/f4914adeefef5dd8074c3e9f6a650513 to your computer and use it in GitHub Desktop.
Save edefazio/f4914adeefef5dd8074c3e9f6a650513 to your computer and use it in GitHub Desktop.
build JavaPoet models and compile / load and use dynamic instances at runtime with Adhoc
package com.squareup.javapoet.adhoc;
import com.squareup.javapoet.*;
import javax.lang.model.element.Modifier;
import junit.framework.TestCase;
import run.adhoc.*;
/**
* Show how to work with the JavaPoetAdhoc abstraction, to compile/load and
* use dynamically build code from JavaPoet models.
*
* @author Eric
*/
public class JavaPoetAdhocTest extends TestCase {
MethodSpec main = MethodSpec.methodBuilder("main")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(void.class)
.addParameter(String[].class, "args")
.addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
.build();
MethodSpec instanceM = MethodSpec.methodBuilder("getIDouble")
.addModifiers(Modifier.PUBLIC)
.returns(int.class)
.addCode("return i+i;")
.build();
//this is a simple Type in JavaParser
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main) //static main method
.addMethod(instanceM)
.addField(int.class, "i", Modifier.PUBLIC)
.addField(int.class, "ID", Modifier.PUBLIC, Modifier.STATIC)
.build();
//this is the "top level" JavaParser type
JavaFile javapoetModel = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
public void testIntegrationToWithJavaPoet(){
//compile & load the JavaPoet model as a new Class
Adhoc adhoc = JavaPoetAdhoc.INSTANCE.load(javapoetModel); //compiled loaded and ready to use
//build & proxy a new instance of "com.example.helloworld.HelloWorld.class"
Proxy p = adhoc.proxy(javapoetModel);
p.set("i", 100); //set instance var
assertEquals(100, p.get("i"));//get instance var
assertEquals(200, p.call("getIDouble")); //call an instance method
p.main(); //call the static main method
}
}
@edefazio
Copy link
Author

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