Metaprogramming
Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at run time.
- Ability to read, generate, transform or modify programs dynamically (at runtime);
- Has the objective of increasing performance, since reflection has high costs.
JavaPoet
JavaPoet is a Java API for generating .java source files.
JavaFile
Represents a Java file containing a single top level class.
Example:
val file = JavaFile
.builder("com.example", typeSpec)
.build()
TypeSpec
Represents a generated class, interface, or enum declaration.
Example:
val typeSpec = TypeSpec
.classBuilder("MyClass")
.addField(fieldSpec)
.addMethod(methodSpec)
.build()
FieldSpec
Represents a generated field declaration.
Example:
val fieldSpec = FieldSpec
.builder(String::class.java)
.addModifiers(Modifier.PRIVATE)
.build()
MethodSpec
Represents a generated constructor or method declaration.
Example:
val methodSpec = MethodSpec
.methodBuilder("myMethod")
.addModifiers(Modifier.PUBLIC)
.addParameter(parameterSpec)
.returns(String::class.java)
.addStatement("return \"Hello, World!\"")
.build()
To define a constructor, use the constructorBuilder method instead of methodBuilder.
ParameterSpec
Represents a generated parameter declaration.
It is not very used, since the parameters are defined directly in the addParameter method.