JavaPoet is a Java API for generating .java source files programmatically with support for modern Java features including records and sealed types
TypeSpec is the specification for type declarations including classes, interfaces, enums, records, and annotation types. It provides a fluent API for building complete type definitions with fields, methods, nested types, and more.
Create builders for different types of declarations.
/**
* Creates a builder for a class declaration
* @param name - The simple name of the class
* @return Builder for configuring a class
*/
static TypeSpec.Builder classBuilder(String name);
/**
* Creates a builder for a class declaration with ClassName
* @param className - The fully-qualified class name
* @return Builder for configuring a class
*/
static TypeSpec.Builder classBuilder(ClassName className);
/**
* Creates a builder for a record class declaration
* @param name - The simple name of the record
* @return Builder for configuring a record
*/
static TypeSpec.Builder recordBuilder(String name);
/**
* Creates a builder for a record class with ClassName
* @param className - The fully-qualified record name
* @return Builder for configuring a record
*/
static TypeSpec.Builder recordBuilder(ClassName className);
/**
* Creates a builder for an interface declaration
* @param name - The simple name of the interface
* @return Builder for configuring an interface
*/
static TypeSpec.Builder interfaceBuilder(String name);
/**
* Creates a builder for an interface with ClassName
* @param className - The fully-qualified interface name
* @return Builder for configuring an interface
*/
static TypeSpec.Builder interfaceBuilder(ClassName className);
/**
* Creates a builder for an enum declaration
* @param name - The simple name of the enum
* @return Builder for configuring an enum
*/
static TypeSpec.Builder enumBuilder(String name);
/**
* Creates a builder for an enum with ClassName
* @param className - The fully-qualified enum name
* @return Builder for configuring an enum
*/
static TypeSpec.Builder enumBuilder(ClassName className);
/**
* Creates a builder for an annotation type declaration
* @param name - The simple name of the annotation
* @return Builder for configuring an annotation type
*/
static TypeSpec.Builder annotationBuilder(String name);
/**
* Creates a builder for an annotation type with ClassName
* @param className - The fully-qualified annotation name
* @return Builder for configuring an annotation type
*/
static TypeSpec.Builder annotationBuilder(ClassName className);
/**
* Creates a builder for an anonymous class
* @param format - Format string for constructor arguments
* @param args - Arguments for format placeholders
* @return Builder for configuring an anonymous class
*/
static TypeSpec.Builder anonymousClassBuilder(String format, Object... args);
/**
* Creates a builder for an anonymous class with CodeBlock
* @param typeArgumentsFormat - CodeBlock for constructor arguments
* @return Builder for configuring an anonymous class
*/
static TypeSpec.Builder anonymousClassBuilder(CodeBlock typeArgumentsFormat);Usage Examples:
// Create a simple class
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.build();
// Create an interface
TypeSpec repository = TypeSpec.interfaceBuilder("Repository")
.addModifiers(Modifier.PUBLIC)
.build();
// Create an enum
TypeSpec color = TypeSpec.enumBuilder("Color")
.addEnumConstant("RED")
.addEnumConstant("GREEN")
.addEnumConstant("BLUE")
.build();
// Create a record
TypeSpec point = TypeSpec.recordBuilder("Point")
.addField(int.class, "x")
.addField(int.class, "y")
.build();
// Create an anonymous class
TypeSpec comparator = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class))
.addMethod(compareMethod)
.build();Access the properties of a TypeSpec.
/**
* Returns the kind of type (CLASS, INTERFACE, ENUM, RECORD, ANNOTATION)
* @return The TypeSpec.Kind enum value
*/
TypeSpec.Kind kind();
/**
* Returns the simple name of the type
* @return The type name (null for anonymous classes)
*/
String name();
/**
* Returns the constructor arguments for anonymous classes
* @return CodeBlock of constructor arguments
*/
CodeBlock anonymousTypeArguments();
/**
* Returns the Javadoc comment
* @return CodeBlock containing Javadoc
*/
CodeBlock javadoc();
/**
* Returns the annotations on this type
* @return List of AnnotationSpec
*/
List<AnnotationSpec> annotations();
/**
* Returns the modifiers for this type
* @return Set of Modifier
*/
Set<Modifier> modifiers();
/**
* Returns the type variables declared by this type
* @return List of TypeVariableName
*/
List<TypeVariableName> typeVariables();
/**
* Returns the superclass type
* @return TypeName of the superclass
*/
TypeName superclass();
/**
* Returns the superinterfaces implemented by this type
* @return List of TypeName for interfaces
*/
List<TypeName> superinterfaces();
/**
* Returns the enum constants defined in this enum type
* @return Map of enum constant names to TypeSpec
*/
Map<String, TypeSpec> enumConstants();
/**
* Returns the fields declared in this type
* @return List of FieldSpec
*/
List<FieldSpec> fieldSpecs();
/**
* Returns the static initializer block
* @return CodeBlock for static initialization
*/
CodeBlock staticBlock();
/**
* Returns the instance initializer block
* @return CodeBlock for instance initialization
*/
CodeBlock initializerBlock();
/**
* Returns the methods declared in this type
* @return List of MethodSpec
*/
List<MethodSpec> methodSpecs();
/**
* Returns the nested types declared in this type
* @return List of nested TypeSpec
*/
List<TypeSpec> typeSpecs();
/**
* Returns the simple names of nested types
* @return Set of nested type names
*/
Set<String> nestedTypesSimpleNames();
/**
* Returns elements that originated this type (for annotation processing)
* @return Set of originating Element
*/
Set<Element> originatingElements();
/**
* Returns names that should always be fully qualified
* @return Set of names to always qualify
*/
Set<String> alwaysQualifiedNames();Convert to a builder for modification.
/**
* Creates a builder initialized with this type's properties
* @return Builder for modifying this TypeSpec
*/
TypeSpec.Builder toBuilder();The builder for configuring TypeSpec instances.
Add Javadoc comments to the type.
/**
* Adds Javadoc documentation from a format string
* @param format - Format string for Javadoc
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
TypeSpec.Builder addJavadoc(String format, Object... args);
/**
* Adds Javadoc documentation from a CodeBlock
* @param block - CodeBlock containing Javadoc
* @return This builder for chaining
*/
TypeSpec.Builder addJavadoc(CodeBlock block);Usage Example:
TypeSpec service = TypeSpec.classBuilder("UserService")
.addJavadoc("Service for managing user operations.\n")
.addJavadoc("\n")
.addJavadoc("<p>This service provides CRUD operations for {@link User} entities.\n")
.build();Add annotations to the type declaration.
/**
* Adds multiple annotations
* @param annotationSpecs - Iterable of annotations to add
* @return This builder for chaining
*/
TypeSpec.Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs);
/**
* Adds an annotation from an AnnotationSpec
* @param annotationSpec - The annotation to add
* @return This builder for chaining
*/
TypeSpec.Builder addAnnotation(AnnotationSpec annotationSpec);
/**
* Adds an annotation by ClassName
* @param annotation - The annotation class name
* @return This builder for chaining
*/
TypeSpec.Builder addAnnotation(ClassName annotation);
/**
* Adds an annotation by Class
* @param annotation - The annotation class
* @return This builder for chaining
*/
TypeSpec.Builder addAnnotation(Class<?> annotation);Usage Example:
TypeSpec entity = TypeSpec.classBuilder("User")
.addAnnotation(AnnotationSpec.builder(Entity.class)
.addMember("name", "$S", "users")
.build())
.addAnnotation(Table.class)
.build();Add modifiers to the type declaration.
/**
* Adds modifiers to the type (e.g., PUBLIC, FINAL, ABSTRACT)
* @param modifiers - Modifiers to add
* @return This builder for chaining
*/
TypeSpec.Builder addModifiers(Modifier... modifiers);Usage Example:
TypeSpec utils = TypeSpec.classBuilder("Utils")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.build();Add generic type parameters to the type declaration.
/**
* Adds multiple type variables (generic parameters)
* @param typeVariables - Iterable of type variables to add
* @return This builder for chaining
*/
TypeSpec.Builder addTypeVariables(Iterable<TypeVariableName> typeVariables);
/**
* Adds a type variable (generic parameter)
* @param typeVariable - The type variable to add
* @return This builder for chaining
*/
TypeSpec.Builder addTypeVariable(TypeVariableName typeVariable);Usage Example:
TypeSpec container = TypeSpec.classBuilder("Container")
.addTypeVariable(TypeVariableName.get("T"))
.addTypeVariable(TypeVariableName.get("E", Comparable.class))
.build();Set the superclass for the type.
/**
* Sets the superclass by TypeName
* @param superclass - The superclass type
* @return This builder for chaining
*/
TypeSpec.Builder superclass(TypeName superclass);
/**
* Sets the superclass by reflection Type
* @param superclass - The superclass type
* @return This builder for chaining
*/
TypeSpec.Builder superclass(Type superclass);
/**
* Sets the superclass with clash avoidance option
* @param superclass - The superclass type
* @param avoidNestedTypeNameClashes - Whether to avoid name clashes
* @return This builder for chaining
*/
TypeSpec.Builder superclass(Type superclass, boolean avoidNestedTypeNameClashes);
/**
* Sets the superclass from TypeMirror
* @param superclass - The superclass type mirror
* @return This builder for chaining
*/
TypeSpec.Builder superclass(TypeMirror superclass);
/**
* Sets the superclass from TypeMirror with clash avoidance
* @param superclass - The superclass type mirror
* @param avoidNestedTypeNameClashes - Whether to avoid name clashes
* @return This builder for chaining
*/
TypeSpec.Builder superclass(TypeMirror superclass, boolean avoidNestedTypeNameClashes);Usage Example:
TypeSpec repository = TypeSpec.classBuilder("UserRepository")
.superclass(ParameterizedTypeName.get(
ClassName.get("com.example", "BaseRepository"),
ClassName.get("com.example", "User")))
.build();Add interfaces implemented by the type.
/**
* Adds multiple superinterfaces
* @param superinterfaces - Iterable of interface types to implement
* @return This builder for chaining
*/
TypeSpec.Builder addSuperinterfaces(Iterable<? extends TypeName> superinterfaces);
/**
* Adds a superinterface by TypeName
* @param superinterface - The interface type to implement
* @return This builder for chaining
*/
TypeSpec.Builder addSuperinterface(TypeName superinterface);
/**
* Adds a superinterface by reflection Type
* @param superinterface - The interface type to implement
* @return This builder for chaining
*/
TypeSpec.Builder addSuperinterface(Type superinterface);
/**
* Adds a superinterface with clash avoidance option
* @param superinterface - The interface type to implement
* @param avoidNestedTypeNameClashes - Whether to avoid name clashes
* @return This builder for chaining
*/
TypeSpec.Builder addSuperinterface(Type superinterface, boolean avoidNestedTypeNameClashes);
/**
* Adds a superinterface from TypeMirror
* @param superinterface - The interface type mirror
* @return This builder for chaining
*/
TypeSpec.Builder addSuperinterface(TypeMirror superinterface);
/**
* Adds a superinterface from TypeMirror with clash avoidance
* @param superinterface - The interface type mirror
* @param avoidNestedTypeNameClashes - Whether to avoid name clashes
* @return This builder for chaining
*/
TypeSpec.Builder addSuperinterface(TypeMirror superinterface, boolean avoidNestedTypeNameClashes);Usage Example:
TypeSpec service = TypeSpec.classBuilder("UserService")
.addSuperinterface(Serializable.class)
.addSuperinterface(ClassName.get("com.example", "Service"))
.build();Add permitted subclasses for sealed types.
/**
* Adds multiple permitted subclasses for sealed types
* @param permittedSubclasses - Iterable of permitted subclass types
* @return This builder for chaining
*/
TypeSpec.Builder addPermittedSubclasses(Iterable<? extends TypeName> permittedSubclasses);
/**
* Adds a permitted subclass by TypeName
* @param permittedSubclass - The permitted subclass type
* @return This builder for chaining
*/
TypeSpec.Builder addPermittedSubclass(TypeName permittedSubclass);
/**
* Adds a permitted subclass by reflection Type
* @param permittedSubclass - The permitted subclass type
* @return This builder for chaining
*/
TypeSpec.Builder addPermittedSubclass(Type permittedSubclass);
/**
* Adds a permitted subclass with clash avoidance option
* @param permittedSubclass - The permitted subclass type
* @param avoidNestedTypeNameClashes - Whether to avoid name clashes
* @return This builder for chaining
*/
TypeSpec.Builder addPermittedSubclass(Type permittedSubclass, boolean avoidNestedTypeNameClashes);
/**
* Adds a permitted subclass from TypeMirror
* @param permittedSubclass - The permitted subclass type mirror
* @return This builder for chaining
*/
TypeSpec.Builder addPermittedSubclass(TypeMirror permittedSubclass);
/**
* Adds a permitted subclass from TypeMirror with clash avoidance
* @param permittedSubclass - The permitted subclass type mirror
* @param avoidNestedTypeNameClashes - Whether to avoid name clashes
* @return This builder for chaining
*/
TypeSpec.Builder addPermittedSubclass(TypeMirror permittedSubclass, boolean avoidNestedTypeNameClashes);Usage Example:
TypeSpec shape = TypeSpec.classBuilder("Shape")
.addModifiers(Modifier.PUBLIC, Modifier.SEALED)
.addPermittedSubclass(ClassName.get("com.example", "Circle"))
.addPermittedSubclass(ClassName.get("com.example", "Rectangle"))
.build();Add constants to enum types.
/**
* Adds an enum constant with default implementation
* @param name - The name of the enum constant
* @return This builder for chaining
*/
TypeSpec.Builder addEnumConstant(String name);
/**
* Adds an enum constant with custom implementation
* @param name - The name of the enum constant
* @param typeSpec - Anonymous class spec for the constant
* @return This builder for chaining
*/
TypeSpec.Builder addEnumConstant(String name, TypeSpec typeSpec);Usage Example:
TypeSpec operation = TypeSpec.enumBuilder("Operation")
.addEnumConstant("PLUS", TypeSpec.anonymousClassBuilder("")
.addMethod(MethodSpec.methodBuilder("apply")
.addModifiers(Modifier.PUBLIC)
.returns(int.class)
.addParameter(int.class, "a")
.addParameter(int.class, "b")
.addStatement("return a + b")
.build())
.build())
.addEnumConstant("MINUS")
.build();Add field declarations to the type.
/**
* Adds multiple fields
* @param fieldSpecs - Iterable of field specifications
* @return This builder for chaining
*/
TypeSpec.Builder addFields(Iterable<FieldSpec> fieldSpecs);
/**
* Adds a field from a FieldSpec
* @param fieldSpec - The field specification
* @return This builder for chaining
*/
TypeSpec.Builder addField(FieldSpec fieldSpec);
/**
* Adds a field with simple configuration
* @param type - The field type
* @param name - The field name
* @param modifiers - The field modifiers
* @return This builder for chaining
*/
TypeSpec.Builder addField(TypeName type, String name, Modifier... modifiers);
/**
* Adds a field using reflection Type
* @param type - The field type
* @param name - The field name
* @param modifiers - The field modifiers
* @return This builder for chaining
*/
TypeSpec.Builder addField(Type type, String name, Modifier... modifiers);Usage Example:
TypeSpec user = TypeSpec.classBuilder("User")
.addField(String.class, "name", Modifier.PRIVATE)
.addField(FieldSpec.builder(int.class, "age")
.addModifiers(Modifier.PRIVATE)
.initializer("$L", 0)
.build())
.build();Add static and instance initializer blocks.
/**
* Adds a static initializer block
* @param block - CodeBlock for static initialization
* @return This builder for chaining
*/
TypeSpec.Builder addStaticBlock(CodeBlock block);
/**
* Adds an instance initializer block
* @param block - CodeBlock for instance initialization
* @return This builder for chaining
*/
TypeSpec.Builder addInitializerBlock(CodeBlock block);Usage Example:
TypeSpec config = TypeSpec.classBuilder("Config")
.addField(Map.class, "settings", Modifier.PRIVATE, Modifier.STATIC)
.addStaticBlock(CodeBlock.builder()
.addStatement("settings = new $T<>()", HashMap.class)
.addStatement("settings.put($S, $S)", "version", "1.0")
.build())
.build();Add method and constructor declarations.
/**
* Adds multiple methods
* @param methodSpecs - Iterable of method specifications
* @return This builder for chaining
*/
TypeSpec.Builder addMethods(Iterable<MethodSpec> methodSpecs);
/**
* Adds a method or constructor
* @param methodSpec - The method specification
* @return This builder for chaining
*/
TypeSpec.Builder addMethod(MethodSpec methodSpec);Usage Example:
MethodSpec getName = MethodSpec.methodBuilder("getName")
.addModifiers(Modifier.PUBLIC)
.returns(String.class)
.addStatement("return name")
.build();
TypeSpec user = TypeSpec.classBuilder("User")
.addField(String.class, "name", Modifier.PRIVATE)
.addMethod(getName)
.build();Set the canonical constructor for record types.
/**
* Sets the canonical constructor for a record
* @param methodSpec - The constructor method spec
* @return This builder for chaining
*/
TypeSpec.Builder recordConstructor(MethodSpec methodSpec);Usage Example:
MethodSpec constructor = MethodSpec.compactConstructorBuilder()
.addStatement("$T.requireNonNull(name)", Objects.class)
.build();
TypeSpec person = TypeSpec.recordBuilder("Person")
.addField(String.class, "name")
.recordConstructor(constructor)
.build();Add nested type declarations.
/**
* Adds multiple nested types
* @param typeSpecs - Iterable of nested type specifications
* @return This builder for chaining
*/
TypeSpec.Builder addTypes(Iterable<TypeSpec> typeSpecs);
/**
* Adds a nested type
* @param typeSpec - The nested type specification
* @return This builder for chaining
*/
TypeSpec.Builder addType(TypeSpec typeSpec);Usage Example:
TypeSpec inner = TypeSpec.classBuilder("Node")
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
.build();
TypeSpec outer = TypeSpec.classBuilder("LinkedList")
.addType(inner)
.build();Configure annotation processing metadata.
/**
* Adds an originating element for annotation processing
* @param element - The originating element
* @return This builder for chaining
*/
TypeSpec.Builder addOriginatingElement(Element element);
/**
* Marks type names to always qualify (never import)
* @param simpleNames - Names to always fully qualify
* @return This builder for chaining
*/
TypeSpec.Builder alwaysQualify(String... simpleNames);
/**
* Avoids name clashes with nested classes of a TypeElement
* @param typeElement - The type element to check against
* @return This builder for chaining
*/
TypeSpec.Builder avoidClashesWithNestedClasses(TypeElement typeElement);
/**
* Avoids name clashes with nested classes of a Class
* @param clazz - The class to check against
* @return This builder for chaining
*/
TypeSpec.Builder avoidClashesWithNestedClasses(Class<?> clazz);Build the final TypeSpec instance.
/**
* Builds the TypeSpec with configured properties
* @return The built TypeSpec instance
*/
TypeSpec build();class TypeSpec {
static Builder classBuilder(String name);
static Builder classBuilder(ClassName className);
static Builder recordBuilder(String name);
static Builder recordBuilder(ClassName className);
static Builder interfaceBuilder(String name);
static Builder interfaceBuilder(ClassName className);
static Builder enumBuilder(String name);
static Builder enumBuilder(ClassName className);
static Builder annotationBuilder(String name);
static Builder annotationBuilder(ClassName className);
static Builder anonymousClassBuilder(String format, Object... args);
static Builder anonymousClassBuilder(CodeBlock typeArgumentsFormat);
Kind kind();
String name();
CodeBlock anonymousTypeArguments();
CodeBlock javadoc();
List<AnnotationSpec> annotations();
Set<Modifier> modifiers();
List<TypeVariableName> typeVariables();
TypeName superclass();
List<TypeName> superinterfaces();
Map<String, TypeSpec> enumConstants();
List<FieldSpec> fieldSpecs();
CodeBlock staticBlock();
CodeBlock initializerBlock();
List<MethodSpec> methodSpecs();
List<TypeSpec> typeSpecs();
Set<String> nestedTypesSimpleNames();
Set<Element> originatingElements();
Set<String> alwaysQualifiedNames();
Builder toBuilder();
boolean equals(Object o);
int hashCode();
String toString();
enum Kind {
CLASS,
RECORD,
INTERFACE,
ENUM,
ANNOTATION
}
}
class TypeSpec.Builder {
TypeSpec.Builder addJavadoc(String format, Object... args);
TypeSpec.Builder addJavadoc(CodeBlock block);
TypeSpec.Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs);
TypeSpec.Builder addAnnotation(AnnotationSpec annotationSpec);
TypeSpec.Builder addAnnotation(ClassName annotation);
TypeSpec.Builder addAnnotation(Class<?> annotation);
TypeSpec.Builder addModifiers(Modifier... modifiers);
TypeSpec.Builder addTypeVariables(Iterable<TypeVariableName> typeVariables);
TypeSpec.Builder addTypeVariable(TypeVariableName typeVariable);
TypeSpec.Builder superclass(TypeName superclass);
TypeSpec.Builder superclass(Type superclass);
TypeSpec.Builder superclass(Type superclass, boolean avoidNestedTypeNameClashes);
TypeSpec.Builder superclass(TypeMirror superclass);
TypeSpec.Builder superclass(TypeMirror superclass, boolean avoidNestedTypeNameClashes);
TypeSpec.Builder addSuperinterfaces(Iterable<? extends TypeName> superinterfaces);
TypeSpec.Builder addSuperinterface(TypeName superinterface);
TypeSpec.Builder addSuperinterface(Type superinterface);
TypeSpec.Builder addSuperinterface(Type superinterface, boolean avoidNestedTypeNameClashes);
TypeSpec.Builder addSuperinterface(TypeMirror superinterface);
TypeSpec.Builder addSuperinterface(TypeMirror superinterface, boolean avoidNestedTypeNameClashes);
TypeSpec.Builder addPermittedSubclasses(Iterable<? extends TypeName> permittedSubclasses);
TypeSpec.Builder addPermittedSubclass(TypeName permittedSubclass);
TypeSpec.Builder addPermittedSubclass(Type permittedSubclass);
TypeSpec.Builder addPermittedSubclass(Type permittedSubclass, boolean avoidNestedTypeNameClashes);
TypeSpec.Builder addPermittedSubclass(TypeMirror permittedSubclass);
TypeSpec.Builder addPermittedSubclass(TypeMirror permittedSubclass, boolean avoidNestedTypeNameClashes);
TypeSpec.Builder addEnumConstant(String name);
TypeSpec.Builder addEnumConstant(String name, TypeSpec typeSpec);
TypeSpec.Builder addFields(Iterable<FieldSpec> fieldSpecs);
TypeSpec.Builder addField(FieldSpec fieldSpec);
TypeSpec.Builder addField(TypeName type, String name, Modifier... modifiers);
TypeSpec.Builder addField(Type type, String name, Modifier... modifiers);
TypeSpec.Builder addStaticBlock(CodeBlock block);
TypeSpec.Builder addInitializerBlock(CodeBlock block);
TypeSpec.Builder addMethods(Iterable<MethodSpec> methodSpecs);
TypeSpec.Builder addMethod(MethodSpec methodSpec);
TypeSpec.Builder recordConstructor(MethodSpec methodSpec);
TypeSpec.Builder addTypes(Iterable<TypeSpec> typeSpecs);
TypeSpec.Builder addType(TypeSpec typeSpec);
TypeSpec.Builder addOriginatingElement(Element element);
TypeSpec.Builder alwaysQualify(String... simpleNames);
TypeSpec.Builder avoidClashesWithNestedClasses(TypeElement typeElement);
TypeSpec.Builder avoidClashesWithNestedClasses(Class<?> clazz);
TypeSpec build();
}Install with Tessl CLI
npx tessl i tessl/maven-com-palantir-javapoet--javapoet@0.11.0docs