JavaPoet is a Java API for generating .java source files programmatically with support for modern Java features including records and sealed types
MethodSpec is the specification for method and constructor declarations. It provides a fluent API for building complete method definitions with parameters, return types, exceptions, and code bodies.
Create builders for methods and constructors.
/**
* Creates a builder for a method declaration
* @param name - The method name
* @return Builder for configuring a method
*/
static MethodSpec.Builder methodBuilder(String name);
/**
* Creates a builder for a constructor declaration
* @return Builder for configuring a constructor
*/
static MethodSpec.Builder constructorBuilder();
/**
* Creates a builder for a compact constructor (for records)
* @return Builder for configuring a compact constructor
*/
static MethodSpec.Builder compactConstructorBuilder();
/**
* Creates a method that overrides an executable element
* @param method - The executable element to override
* @return Builder initialized as an override
*/
static MethodSpec.Builder overriding(ExecutableElement method);
/**
* Creates a method that overrides with type resolution
* @param method - The executable element to override
* @param enclosing - The declaring type
* @param types - Type utilities for resolution
* @return Builder initialized as an override
*/
static MethodSpec.Builder overriding(ExecutableElement method, DeclaredType enclosing, Types types);Usage Examples:
// Create a simple method
MethodSpec hello = MethodSpec.methodBuilder("sayHello")
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addStatement("$T.out.println($S)", System.class, "Hello!")
.build();
// Create a constructor
MethodSpec constructor = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addParameter(String.class, "name")
.addStatement("this.name = name")
.build();
// Create a compact constructor for records
MethodSpec compactConstructor = MethodSpec.compactConstructorBuilder()
.addStatement("$T.requireNonNull(name)", Objects.class)
.build();
// Override a method from interface
MethodSpec override = MethodSpec.overriding(executableElement)
.addStatement("// implementation")
.build();Access the properties of a MethodSpec.
/**
* Returns the method name
* @return The method name (empty for constructors)
*/
String name();
/**
* Returns the Javadoc comment
* @return CodeBlock containing Javadoc
*/
CodeBlock javadoc();
/**
* Returns the annotations on this method
* @return List of AnnotationSpec
*/
List<AnnotationSpec> annotations();
/**
* Returns the modifiers for this method
* @return Set of Modifier
*/
Set<Modifier> modifiers();
/**
* Returns the type variables declared by this method
* @return List of TypeVariableName for generic parameters
*/
List<TypeVariableName> typeVariables();
/**
* Returns the return type
* @return TypeName of the return type
*/
TypeName returnType();
/**
* Returns the parameters of this method
* @return List of ParameterSpec
*/
List<ParameterSpec> parameters();
/**
* Checks if this method uses varargs
* @return true if varargs, false otherwise
*/
boolean varargs();
/**
* Returns the exception types thrown by this method
* @return List of TypeName for exceptions
*/
List<TypeName> exceptions();
/**
* Returns the method body code
* @return CodeBlock containing the method implementation
*/
CodeBlock code();
/**
* Returns the default value for annotation methods
* @return CodeBlock for default value (null if not annotation method)
*/
CodeBlock defaultValue();
/**
* Checks if this is a constructor
* @return true if constructor, false if regular method
*/
boolean isConstructor();Convert to a builder for modification.
/**
* Creates a builder initialized with this method's properties
* @return Builder for modifying this MethodSpec
*/
MethodSpec.Builder toBuilder();The builder for configuring MethodSpec instances.
Set or change the method name.
/**
* Sets the method name
* @param name - The new method name
* @return This builder for chaining
*/
MethodSpec.Builder setName(String name);Add Javadoc comments to the method.
/**
* Adds Javadoc documentation from a format string
* @param format - Format string for Javadoc
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
MethodSpec.Builder addJavadoc(String format, Object... args);
/**
* Adds Javadoc documentation from a CodeBlock
* @param block - CodeBlock containing Javadoc
* @return This builder for chaining
*/
MethodSpec.Builder addJavadoc(CodeBlock block);Usage Example:
MethodSpec process = MethodSpec.methodBuilder("process")
.addJavadoc("Processes the input data and returns the result.\n")
.addJavadoc("\n")
.addJavadoc("@param data the data to process\n")
.addJavadoc("@return the processed result\n")
.build();Add annotations to the method declaration.
/**
* Adds multiple annotations
* @param annotationSpecs - Iterable of annotations to add
* @return This builder for chaining
*/
MethodSpec.Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs);
/**
* Adds an annotation from an AnnotationSpec
* @param annotationSpec - The annotation to add
* @return This builder for chaining
*/
MethodSpec.Builder addAnnotation(AnnotationSpec annotationSpec);
/**
* Adds an annotation by ClassName
* @param annotation - The annotation class name
* @return This builder for chaining
*/
MethodSpec.Builder addAnnotation(ClassName annotation);
/**
* Adds an annotation by Class
* @param annotation - The annotation class
* @return This builder for chaining
*/
MethodSpec.Builder addAnnotation(Class<?> annotation);Usage Example:
MethodSpec deprecated = MethodSpec.methodBuilder("oldMethod")
.addAnnotation(Deprecated.class)
.addAnnotation(Override.class)
.build();Add modifiers to the method declaration.
/**
* Adds modifiers to the method (e.g., PUBLIC, STATIC, FINAL)
* @param modifiers - Modifiers to add
* @return This builder for chaining
*/
MethodSpec.Builder addModifiers(Modifier... modifiers);
/**
* Adds modifiers from an iterable
* @param modifiers - Iterable of modifiers to add
* @return This builder for chaining
*/
MethodSpec.Builder addModifiers(Iterable<Modifier> modifiers);Usage Example:
MethodSpec helper = MethodSpec.methodBuilder("helper")
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
.build();Add generic type parameters to the method.
/**
* Adds multiple type variables (generic parameters)
* @param typeVariables - Iterable of type variables to add
* @return This builder for chaining
*/
MethodSpec.Builder addTypeVariables(Iterable<TypeVariableName> typeVariables);
/**
* Adds a type variable (generic parameter)
* @param typeVariable - The type variable to add
* @return This builder for chaining
*/
MethodSpec.Builder addTypeVariable(TypeVariableName typeVariable);Usage Example:
MethodSpec generic = MethodSpec.methodBuilder("transform")
.addTypeVariable(TypeVariableName.get("T"))
.addTypeVariable(TypeVariableName.get("R"))
.addParameter(TypeVariableName.get("T"), "input")
.returns(TypeVariableName.get("R"))
.build();Set the return type for the method.
/**
* Sets the return type by TypeName
* @param returnType - The return type
* @return This builder for chaining
*/
MethodSpec.Builder returns(TypeName returnType);
/**
* Sets the return type by reflection Type
* @param returnType - The return type
* @return This builder for chaining
*/
MethodSpec.Builder returns(Type returnType);Usage Example:
MethodSpec getString = MethodSpec.methodBuilder("getString")
.returns(String.class)
.addStatement("return value")
.build();
MethodSpec getList = MethodSpec.methodBuilder("getList")
.returns(ParameterizedTypeName.get(List.class, String.class))
.addStatement("return items")
.build();Add parameters to the method.
/**
* Adds multiple parameters
* @param parameterSpecs - Iterable of parameter specifications
* @return This builder for chaining
*/
MethodSpec.Builder addParameters(Iterable<ParameterSpec> parameterSpecs);
/**
* Adds a parameter from a ParameterSpec
* @param parameterSpec - The parameter specification
* @return This builder for chaining
*/
MethodSpec.Builder addParameter(ParameterSpec parameterSpec);
/**
* Adds a parameter with simple configuration
* @param type - The parameter type
* @param name - The parameter name
* @param modifiers - The parameter modifiers
* @return This builder for chaining
*/
MethodSpec.Builder addParameter(TypeName type, String name, Modifier... modifiers);
/**
* Adds a parameter using reflection Type
* @param type - The parameter type
* @param name - The parameter name
* @param modifiers - The parameter modifiers
* @return This builder for chaining
*/
MethodSpec.Builder addParameter(Type type, String name, Modifier... modifiers);Usage Example:
MethodSpec calculate = MethodSpec.methodBuilder("calculate")
.addParameter(int.class, "a")
.addParameter(int.class, "b")
.addParameter(ParameterSpec.builder(String.class, "operation")
.addAnnotation(Nullable.class)
.build())
.returns(int.class)
.build();Set whether the method uses varargs.
/**
* Marks the method as using varargs
* @return This builder for chaining
*/
MethodSpec.Builder varargs();
/**
* Sets whether the method uses varargs
* @param varargs - true for varargs, false otherwise
* @return This builder for chaining
*/
MethodSpec.Builder varargs(boolean varargs);Usage Example:
MethodSpec printf = MethodSpec.methodBuilder("printf")
.addParameter(String.class, "format")
.addParameter(Object[].class, "args")
.varargs()
.build();Add thrown exception types.
/**
* Adds multiple exception types
* @param exceptions - Iterable of exception types
* @return This builder for chaining
*/
MethodSpec.Builder addExceptions(Iterable<? extends TypeName> exceptions);
/**
* Adds an exception type by TypeName
* @param exception - The exception type
* @return This builder for chaining
*/
MethodSpec.Builder addException(TypeName exception);
/**
* Adds an exception type by reflection Type
* @param exception - The exception type
* @return This builder for chaining
*/
MethodSpec.Builder addException(Type exception);Usage Example:
MethodSpec readFile = MethodSpec.methodBuilder("readFile")
.addParameter(String.class, "path")
.returns(String.class)
.addException(IOException.class)
.addException(FileNotFoundException.class)
.build();Add code to the method body using various methods.
/**
* Adds code with named arguments
* @param format - Format string with named placeholders
* @param args - Map of argument names to values
* @return This builder for chaining
*/
MethodSpec.Builder addNamedCode(String format, Map<String, ?> args);
/**
* Adds code from a format string
* @param format - Format string for code
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
MethodSpec.Builder addCode(String format, Object... args);
/**
* Adds code from a CodeBlock
* @param codeBlock - CodeBlock to add
* @return This builder for chaining
*/
MethodSpec.Builder addCode(CodeBlock codeBlock);
/**
* Adds a comment
* @param format - Format string for comment
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
MethodSpec.Builder addComment(String format, Object... args);
/**
* Adds a statement (automatically adds semicolon and newline)
* @param format - Format string for statement
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
MethodSpec.Builder addStatement(String format, Object... args);
/**
* Adds a statement from a CodeBlock
* @param codeBlock - CodeBlock for the statement
* @return This builder for chaining
*/
MethodSpec.Builder addStatement(CodeBlock codeBlock);Usage Examples:
MethodSpec example = MethodSpec.methodBuilder("example")
.addComment("Initialize the counter")
.addStatement("int count = 0")
.addCode("\n")
.addStatement("$T.out.println($S)", System.class, "Count: " + count)
.build();
// Named arguments
Map<String, Object> args = new HashMap<>();
args.put("field", "name");
args.put("value", "John");
MethodSpec setter = MethodSpec.methodBuilder("setName")
.addNamedCode("this.$field:N = $value:S;\n", args)
.build();Add control flow structures to the method body.
/**
* Begins a control flow block (if, for, while, etc.)
* @param controlFlow - Format string for control flow statement
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
MethodSpec.Builder beginControlFlow(String controlFlow, Object... args);
/**
* Begins a control flow block from CodeBlock
* @param codeBlock - CodeBlock for control flow statement
* @return This builder for chaining
*/
MethodSpec.Builder beginControlFlow(CodeBlock codeBlock);
/**
* Adds next control flow (else if, else, catch, etc.)
* @param controlFlow - Format string for next control flow
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
MethodSpec.Builder nextControlFlow(String controlFlow, Object... args);
/**
* Adds next control flow from CodeBlock
* @param codeBlock - CodeBlock for next control flow
* @return This builder for chaining
*/
MethodSpec.Builder nextControlFlow(CodeBlock codeBlock);
/**
* Ends the current control flow block
* @return This builder for chaining
*/
MethodSpec.Builder endControlFlow();
/**
* Ends control flow with a following statement
* @param controlFlow - Format string for ending statement
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
MethodSpec.Builder endControlFlow(String controlFlow, Object... args);
/**
* Ends control flow with a CodeBlock statement
* @param codeBlock - CodeBlock for ending statement
* @return This builder for chaining
*/
MethodSpec.Builder endControlFlow(CodeBlock codeBlock);Usage Examples:
// If-else statement
MethodSpec conditional = MethodSpec.methodBuilder("check")
.beginControlFlow("if (value > 0)")
.addStatement("return true")
.nextControlFlow("else")
.addStatement("return false")
.endControlFlow()
.build();
// For loop
MethodSpec loop = MethodSpec.methodBuilder("iterate")
.beginControlFlow("for (int i = 0; i < 10; i++)")
.addStatement("$T.out.println(i)", System.class)
.endControlFlow()
.build();
// Try-catch
MethodSpec tryCatch = MethodSpec.methodBuilder("safe")
.beginControlFlow("try")
.addStatement("riskyOperation()")
.nextControlFlow("catch ($T e)", Exception.class)
.addStatement("$T.err.println(e)", System.class)
.endControlFlow()
.build();
// Try-finally
MethodSpec tryFinally = MethodSpec.methodBuilder("cleanup")
.beginControlFlow("try")
.addStatement("resource.use()")
.endControlFlow("finally")
.beginControlFlow("")
.addStatement("resource.close()")
.endControlFlow()
.build();Set the default value for annotation methods.
/**
* Sets the default value from a format string
* @param format - Format string for default value
* @param args - Arguments for format placeholders
* @return This builder for chaining
*/
MethodSpec.Builder defaultValue(String format, Object... args);
/**
* Sets the default value from a CodeBlock
* @param codeBlock - CodeBlock for default value
* @return This builder for chaining
*/
MethodSpec.Builder defaultValue(CodeBlock codeBlock);Usage Example:
TypeSpec annotation = TypeSpec.annotationBuilder("MyAnnotation")
.addMethod(MethodSpec.methodBuilder("value")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.returns(String.class)
.defaultValue("$S", "default")
.build())
.addMethod(MethodSpec.methodBuilder("count")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.returns(int.class)
.defaultValue("$L", 0)
.build())
.build();Build the final MethodSpec instance.
/**
* Builds the MethodSpec with configured properties
* @return The built MethodSpec instance
*/
MethodSpec build();class MethodSpec {
static Builder methodBuilder(String name);
static Builder constructorBuilder();
static Builder compactConstructorBuilder();
static Builder overriding(ExecutableElement method);
static Builder overriding(ExecutableElement method, DeclaredType enclosing, Types types);
String name();
CodeBlock javadoc();
List<AnnotationSpec> annotations();
Set<Modifier> modifiers();
List<TypeVariableName> typeVariables();
TypeName returnType();
List<ParameterSpec> parameters();
boolean varargs();
List<TypeName> exceptions();
CodeBlock code();
CodeBlock defaultValue();
boolean isConstructor();
Builder toBuilder();
boolean equals(Object o);
int hashCode();
String toString();
}
class MethodSpec.Builder {
MethodSpec.Builder setName(String name);
MethodSpec.Builder addJavadoc(String format, Object... args);
MethodSpec.Builder addJavadoc(CodeBlock block);
MethodSpec.Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs);
MethodSpec.Builder addAnnotation(AnnotationSpec annotationSpec);
MethodSpec.Builder addAnnotation(ClassName annotation);
MethodSpec.Builder addAnnotation(Class<?> annotation);
MethodSpec.Builder addModifiers(Modifier... modifiers);
MethodSpec.Builder addModifiers(Iterable<Modifier> modifiers);
MethodSpec.Builder addTypeVariables(Iterable<TypeVariableName> typeVariables);
MethodSpec.Builder addTypeVariable(TypeVariableName typeVariable);
MethodSpec.Builder returns(TypeName returnType);
MethodSpec.Builder returns(Type returnType);
MethodSpec.Builder addParameters(Iterable<ParameterSpec> parameterSpecs);
MethodSpec.Builder addParameter(ParameterSpec parameterSpec);
MethodSpec.Builder addParameter(TypeName type, String name, Modifier... modifiers);
MethodSpec.Builder addParameter(Type type, String name, Modifier... modifiers);
MethodSpec.Builder varargs();
MethodSpec.Builder varargs(boolean varargs);
MethodSpec.Builder addExceptions(Iterable<? extends TypeName> exceptions);
MethodSpec.Builder addException(TypeName exception);
MethodSpec.Builder addException(Type exception);
MethodSpec.Builder addNamedCode(String format, Map<String, ?> args);
MethodSpec.Builder addCode(String format, Object... args);
MethodSpec.Builder addCode(CodeBlock codeBlock);
MethodSpec.Builder addComment(String format, Object... args);
MethodSpec.Builder addStatement(String format, Object... args);
MethodSpec.Builder addStatement(CodeBlock codeBlock);
MethodSpec.Builder beginControlFlow(String controlFlow, Object... args);
MethodSpec.Builder beginControlFlow(CodeBlock codeBlock);
MethodSpec.Builder nextControlFlow(String controlFlow, Object... args);
MethodSpec.Builder nextControlFlow(CodeBlock codeBlock);
MethodSpec.Builder endControlFlow();
MethodSpec.Builder endControlFlow(String controlFlow, Object... args);
MethodSpec.Builder endControlFlow(CodeBlock codeBlock);
MethodSpec.Builder defaultValue(String format, Object... args);
MethodSpec.Builder defaultValue(CodeBlock codeBlock);
MethodSpec build();
}Install with Tessl CLI
npx tessl i tessl/maven-com-palantir-javapoet--javapoet@0.11.0docs