Skip to content

Latest commit

 

History

History
80 lines (53 loc) · 2.18 KB

3-metaprogramming.md

File metadata and controls

80 lines (53 loc) · 2.18 KB

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 is a Java API for generating .java source files.

JavaPoet

Represents a Java file containing a single top level class.

Example:

val file = JavaFile
    .builder("com.example", typeSpec)
    .build()

Represents a generated class, interface, or enum declaration.

Example:

val typeSpec = TypeSpec
    .classBuilder("MyClass")
    .addField(fieldSpec)
    .addMethod(methodSpec)
    .build()

Represents a generated field declaration.

Example:

val fieldSpec = FieldSpec
    .builder(String::class.java)
    .addModifiers(Modifier.PRIVATE)
    .build()

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.

Represents a generated parameter declaration.

It is not very used, since the parameters are defined directly in the addParameter method.