Java library used to generate Java source files.
JavaPoet is a Java API for generating .java source files.
Source file generation can be useful when doing things such as annotation processing or interacting with metadata files (e.g., database schemas, protocol formats). By generating code, you eliminate the need to write boilerplate while also keeping a single source of truth for the metadata.
This repo is forked from the excellent square/javapoet project which is no longer actively maintained.
Significant changes:
com.palantir.javapoetprivate and instead added getter methodsTypeSpec#recordBuilder)sealed types (TypeSpec.Builder#addPermittedSubclass)Gradle:
implementation("com.palantir.javapoet:javapoet:")Maven:
com.palantir.javapoet
javapoet
$version$
Here's a (boring) HelloWorld class:
package com.example.helloworld;
public final class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, JavaPoet!");
}
}And this is the (exciting) code to generate it with JavaPoet:
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();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main)
.build();
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
javaFile.writeTo(System.out);To declare the main method, we've created a MethodSpec "main" configured with modifiers, return
type, parameters and code statements. We add the main method to a HelloWorld class, and then add
that to a HelloWorld.java file.
In this case we write the file to System.out, but we could also get it as a string
(JavaFile.toString()) or write it to the file system (JavaFile.writeTo()).
Most of JavaPoet's API uses plain old immutable Java objects. There's also builders, method chaining
and varargs to make the API friendly. JavaPoet offers models for classes & interfaces (TypeSpec),
fields (FieldSpec), methods & constructors (MethodSpec), parameters (ParameterSpec) and
annotations (AnnotationSpec).
But the body of methods and constructors is not modeled. There's no expression class, no statement class or syntax tree nodes. Instead, JavaPoet uses strings for code blocks:
MethodSpec main = MethodSpec.methodBuilder("main")
.addCode(""
+ "int total = 0;\n"
+ "for (int i = 0; i ()", listOfHoverboards, arrayList)
.addStatement("result.add(new $T())", hoverboard)
.addStatement("result.add(new $T())", hoverboard)
.addStatement("result.add(new $T())", hoverboard)
.addStatement("return result")
.build();JavaPoet will decompose each type and import its components where possible.
package com.example.helloworld;
import com.mattel.Hoverboard;
import java.util.ArrayList;
import java.util.List;
public final class HelloWorld {
List beyond() {
List result = new ArrayList<>();
result.add(new Hoverboard());
result.add(new Hoverboard());
result.add(new Hoverboard());
return result;
}
}JavaPoet supports import static. It does it via explicitly collecting type member names. Let's
enhance the previous example with some static sugar:
…JavaPoet will first add your import static block to the file as configured, match and mangle
all calls accordingly and also import all other types as needed.
package com.example.helloworld;
import static com.mattel.Hoverboard.Boards.*;
import static com.mattel.Hoverboard.createNimbus;
import static java.util.Collections.*;
import com.mattel.Hoverboard;
import java.util.ArrayList;
import java.util.List;
class HelloWorld {
List beyond() {
List result = new ArrayList<>();
result.add(createNimbus(2000));
result.add(createNimbus("2001"));
result.add(createNimbus(THUNDERBOLT));
sort(result);
return result.isEmpty() ? emptyList() : result;
}
}Generated code is often self-referential. Use $N to refer to another generated declaration by
its name. Here's a method that calls another:
public String byteToHex(int b) {
char[] result = new char[2];
result[0] = hexDigit((b >>> 4) & 0xf);
result[1] = hexDigit(b & 0xf);
return new String(result);
}
public char hexDigit(int i) {
return (char) (i >> 4) & 0xf)", hexDigit)
.addStatement("result[1] = $N(b & 0xf)", hexDigit)
.addStatement("return new String(result)")
.build();Code blocks may specify the values for their placeholders in a few ways. Only one style may be used for each operation on a code block.
Pass an argument value for each placeholder in the format string to CodeBlock.add(). In each
example, we generate code to say "I ate 3 tacos"
CodeBlock.builder().add("I ate $L $L", 3, "tacos")Place an integer index (1-based) before the placeholder in the format string to specify which argument to use.
CodeBlock.builder().add("I ate $2L $1L", "tacos", 3)Use the syntax $argumentName:X where X is the format character and call CodeBlock.addNamed()
with a map containing all argument keys in the format string. Argument names use characters in
a-z, A-Z, 0-9, and _, and must start with a lowercase character.
Map map = new LinkedHashMap<>();
map.put("food", "tacos");
map.put("count", 3);
CodeBlock.builder().addNamed("I ate $count:L $food:L", map)All of the above methods have a code body. Use Modifiers.ABSTRACT to get a method without any
body. This is only legal if the enclosing class is either abstract or an interface.
MethodSpec flux = MethodSpec.methodBuilder("flux")
.addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED)
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.addMethod(flux)
.build();Which generates this:
public abstract class HelloWorld {
protected abstract void flux();
}The other modifiers work where permitted. Note that when specifying modifiers, JavaPoet uses
javax.lang.model.element.Modifier, a class that is not available on Android. This
limitation applies to code-generating-code only; the output code runs everywhere: JVMs, Android,
and GWT.
Methods also have parameters, exceptions, varargs, Javadoc, annotations, type variables, and a
return type. All of these are configured with MethodSpec.Builder.
MethodSpec is a slight misnomer; it can also be used for constructors:
MethodSpec flux = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addParameter(String.class, "greeting")
.addStatement("this.$N = $N", "greeting", "greeting")
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC)
.addField(String.class, "greeting", Modifier.PRIVATE, Modifier.FINAL)
.addMethod(flux)
.build();Which generates this:
public class HelloWorld {
private final String greeting;
public HelloWorld(String greeting) {
this.greeting = greeting;
}
}For the most part, constructors work just like methods. When emitting code, JavaPoet will place constructors before methods in the output file.
Declare parameters on methods and constructors with either ParameterSpec.builder() or
MethodSpec's convenient addParameter() API:
ParameterSpec android = ParameterSpec.builder(String.class, "android")
.addModifiers(Modifier.FINAL)
.build();
MethodSpec welcomeOverlords = MethodSpec.methodBuilder("welcomeOverlords")
.addParameter(android)
.addParameter(String.class, "robot", Modifier.FINAL)
.build();Though the code above to generate android and robot parameters is different, the output is the
same:
void welcomeOverlords(final String android, final String robot) {
}The extended Builder form is necessary when the parameter has annotations (such as @Nullable).
Like parameters, fields can be created either with builders or by using convenient helper methods:
FieldSpec android = FieldSpec.builder(String.class, "android")
.addModifiers(Modifier.PRIVATE, Modifier.FINAL)
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC)
.addField(android)
.addField(String.class, "robot", Modifier.PRIVATE, Modifier.FINAL)
.build();Which generates:
public class HelloWorld {
private final String android;
private final String robot;
}The extended Builder form is necessary when a field has Javadoc, annotations, or a field
initializer. Field initializers use the same String.format()-like syntax as the code
blocks above:
FieldSpec android = FieldSpec.builder(String.class, "android")
.addModifiers(Modifier.PRIVATE, Modifier.FINAL)
.initializer("$S + $L", "Lollipop v.", 5.0d)
.build();Which generates:
private final String android = "Lollipop v." + 5.0;JavaPoet has no trouble with interfaces. Note that interface methods must always be PUBLIC ABSTRACT and interface fields must always be PUBLIC STATIC FINAL. These modifiers are necessary
when defining the interface:
TypeSpec helloWorld = TypeSpec.interfaceBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC)
.addField(FieldSpec.builder(String.class, "ONLY_THING_THAT_IS_CONSTANT")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$S", "change")
.build())
.addMethod(MethodSpec.methodBuilder("beep")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.build())
.build();But these modifiers are omitted when the code is generated. These are the defaults so we don't need
to include them for javac's benefit!
public interface HelloWorld {
String ONLY_THING_THAT_IS_CONSTANT = "change";
void beep();
}Use enumBuilder to create the enum type, and addEnumConstant() for each value:
TypeSpec helloWorld = TypeSpec.enumBuilder("Roshambo")
.addModifiers(Modifier.PUBLIC)
.addEnumConstant("ROCK")
.addEnumConstant("SCISSORS")
.addEnumConstant("PAPER")
.build();To generate this:
public enum Roshambo {
ROCK,
SCISSORS,
PAPER
}Fancy enums are supported, where the enum values override methods or call a superclass constructor. Here's a comprehensive example:
…Which generates this:
public enum Roshambo {
ROCK("fist") {
@Override
public String toString() {
return "avalanche!";
}
},
SCISSORS("peace"),
PAPER("flat");
private final String handsign;
Roshambo(String handsign) {
this.handsign = handsign;
}
}In the enum code, we used TypeSpec.anonymousInnerClass(). Anonymous inner classes can also be used in
code blocks. They are values that can be referenced with $L:
…This generates a method that contains a class that contains a method:
void sortByLength(List strings) {
Collections.sort(strings, new Comparator() {
@Override
public int compare(String a, String b) {
return a.length() - b.length();
}
});
}One particularly tricky part of defining anonymou
No open issues yet, or sync has not completed.