Java API for generating .java source files programmatically with fluent builder interfaces.
npx @tessl/cli install tessl/maven-com-squareup--javapoet@1.13.0JavaPoet is a Java API for generating .java source files programmatically. It provides a fluent builder API that enables developers to create Java classes, methods, fields, and other code constructs dynamically at runtime or during compilation phases like annotation processing. The library offers immutable model objects for representing Java language elements and handles proper formatting, indentation, imports, and Java syntax rules automatically.
pom.xml:
<dependency>
<groupId>com.squareup</groupId>
<artifactId>javapoet</artifactId>
<version>1.13.0</version>
</dependency>implementation 'com.squareup:javapoet:1.13.0'import com.squareup.javapoet.*;Specific imports for common classes:
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.TypeName;
import javax.lang.model.element.Modifier;import com.squareup.javapoet.*;
import javax.lang.model.element.Modifier;
// Create a method
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();
// Create a class containing the method
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main)
.build();
// Create a Java file containing the class
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
// Write to system output or file
javaFile.writeTo(System.out);JavaPoet is built around several key design patterns:
$L, $S, $T, $N) for safe code generationCore functionality for creating and writing Java source files with proper package structure and import management.
public final class JavaFile {
// Static factory method
public static Builder builder(String packageName, TypeSpec typeSpec);
// Writing methods
public void writeTo(Appendable out) throws IOException;
public void writeTo(Path directory) throws IOException;
public Path writeToPath(Path directory) throws IOException;
public void writeTo(File directory) throws IOException;
public void writeTo(Filer filer) throws IOException;
public JavaFileObject toJavaFileObject();
}Type representation system including basic types, class names, parameterized types, arrays, type variables, and wildcards.
// Base type class
public class TypeName {
// Type constants
public static final TypeName VOID;
public static final TypeName BOOLEAN;
public static final TypeName INT;
public static final TypeName LONG;
// ... other primitives
// Factory methods
public static TypeName get(TypeMirror mirror);
public static TypeName get(Type type);
// Type operations
public TypeName annotated(AnnotationSpec... annotations);
public boolean isPrimitive();
public TypeName box();
public TypeName unbox();
}
// Class names
public final class ClassName extends TypeName implements Comparable<ClassName> {
public static ClassName get(Class<?> clazz);
public static ClassName get(String packageName, String simpleName, String... simpleNames);
public String packageName();
public String simpleName();
public ClassName nestedClass(String name);
}Builders for creating Java language constructs including classes, interfaces, enums, methods, fields, and parameters.
// Type specification
public final class TypeSpec {
public static Builder classBuilder(String name);
public static Builder interfaceBuilder(String name);
public static Builder enumBuilder(String name);
public static Builder annotationBuilder(String name);
}
// Method specification
public final class MethodSpec {
public static Builder methodBuilder(String name);
public static Builder constructorBuilder();
}
// Field specification
public final class FieldSpec {
public static Builder builder(TypeName type, String name, Modifier... modifiers);
}Advanced type representations for complex generic scenarios including parameterized types, arrays, type variables, and wildcards.
// Parameterized types like List<String>
public final class ParameterizedTypeName extends TypeName {
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments);
}
// Array types like String[]
public final class ArrayTypeName extends TypeName {
public static ArrayTypeName of(TypeName componentType);
}
// Type variables like T, E, K, V
public final class TypeVariableName extends TypeName {
public static TypeVariableName get(String name);
public static TypeVariableName get(String name, TypeName... bounds);
}
// Wildcard types like ? extends String
public final class WildcardTypeName extends TypeName {
public static WildcardTypeName subtypeOf(TypeName upperBound);
public static WildcardTypeName supertypeOf(TypeName lowerBound);
}Template-based code generation system and utilities for generating method bodies, initializers, and managing identifier names.
// Code block generation with templates
public final class CodeBlock {
public static CodeBlock of(String format, Object... args);
public static Builder builder();
// Template placeholders:
// $L - Literals (direct substitution)
// $S - Strings (with proper escaping and quotes)
// $T - Types (with automatic import handling)
// $N - Names (for referencing other generated elements)
}
// Name allocation utilities
public final class NameAllocator implements Cloneable {
public String newName(String suggestion);
public String newName(String suggestion, Object tag);
public String get(Object tag);
public static String toJavaIdentifier(String suggestion);
}