Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Outline an annotation processor that generates a Builder class for every class annotated @GenerateBuilder. Show the key methods you would override and how you would write the output.

We extend AbstractProcessor, declare the supported annotation type and return SourceVersion.latestSupported(), and in process() iterate over roundEnv.getElementsAnnotatedWith(GenerateBuilder.class), checking that each element is a class. For each class we read its fields or constructor parameters through ElementFilter and their TypeMirrors, then write a Builder source file with processingEnv.getFiler().createSourceFile, either with a plain Writer or with a library such as JavaPoet. Problems are reported with Messager.printMessage against the offending element, and process() returns false unless we want to claim the annotation from other processors.

Why this question is asked

Writing a small annotation processor is the clearest way to see how tools like MapStruct, Immutables or AutoValue generate code at compile time with no reflection at run time. Interviewers ask for an outline because it shows whether we know the processor API's main pieces and the practical details, such as reporting errors properly and generating code next to the original class. In this answer, we will define the annotation, set up the processor class, find and validate the annotated classes, read their fields, write the builder source, report errors, register the processor, and make it work with Gradle's incremental compilation.

1The Annotation and the Goal

The annotation only needs to exist at compile time, so SOURCE retention is enough: the processor reads it during compilation, and nothing needs it afterwards. It goes on classes.

Java
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface GenerateBuilder { }
@GenerateBuilder
public class Order {
final String id;
final int quantity;
public Order(String id, int quantity) { this.id = id; this.quantity = quantity; }
}
// Goal: generate OrderBuilder so that
Order o = new OrderBuilder().id("A-1").quantity(3).build(); // new Order("A-1", 3)

Notice that we generate a separate OrderBuilder class. A standard processor cannot add a nested Builder inside Order itself, because the processor API only creates new files.

2Setting Up the Processor Class

The processor extends AbstractProcessor. We declare which annotation it handles and which source version it supports. Overriding getSupportedSourceVersion to return latestSupported() avoids a warning every time the project moves to a newer Java release; the @SupportedSourceVersion annotation would pin one version.

Java
@SupportedAnnotationTypes("com.acme.GenerateBuilder")
public final class BuilderProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element e : roundEnv.getElementsAnnotatedWith(GenerateBuilder.class)) {
if (e.getKind() != ElementKind.CLASS) {
error(e, "@GenerateBuilder can only be used on classes");
continue;
}
generate((TypeElement) e);
}
return false; // do not claim the annotation; other processors may also read it
}
}

The kind check matters because @Target(TYPE) also allows interfaces, enums and records. Rather than generate broken code for an interface, we report a clear error and move on. Returning false leaves the annotation available to other processors; returning true would claim it so no later processor is asked about it, which is only appropriate when we own it completely.

3Reading the Fields

For each class we read the inputs to the builder from the element model. Here we use the parameters of the class's constructor with the most parameters, which is the safest choice because it is the way the class itself wants to be built. ElementFilter picks constructors out of the enclosed elements, and each parameter's TypeMirror gives us its type as it should appear in source code.

Java
private void generate(TypeElement type) {
ExecutableElement ctor = ElementFilter.constructorsIn(type.getEnclosedElements()).stream()
.filter(c -> !c.getModifiers().contains(Modifier.PRIVATE))
.max(Comparator.comparingInt(c -> c.getParameters().size()))
.orElse(null);
if (ctor == null) {
error(type, "@GenerateBuilder needs a non-private constructor");
return;
}
List<? extends VariableElement> params = ctor.getParameters(); // id: java.lang.String, quantity: int
String pkg = processingEnv.getElementUtils().getPackageOf(type).getQualifiedName().toString(); // com.acme
String simple = type.getSimpleName().toString(); // Order
write(type, pkg, simple, params);
}

Parameter names are available here because the processor reads the source model. That is one advantage over reflection, where parameter names are only available if the code was compiled with -parameters.

4Writing the Builder Source

We create the file with the Filer, passing the original type as the originating element. That link tells the compiler and build tools which source produced which generated file, which matters for incremental builds. For a small builder a plain Writer is fine; for anything larger, JavaPoet builds the source with proper imports and escaping.

Java
private void write(TypeElement type, String pkg, String simple, List<? extends VariableElement> params) {
String builder = simple + "Builder";
try {
JavaFileObject file = processingEnv.getFiler().createSourceFile(pkg + "." + builder, type);
try (PrintWriter out = new PrintWriter(file.openWriter())) {
out.printf("package %s;%n%n", pkg);
out.printf("@javax.annotation.processing.Generated(\"com.acme.BuilderProcessor\")%n");
out.printf("public final class %s {%n", builder);
for (VariableElement p : params)
out.printf(" private %s %s;%n", p.asType(), p.getSimpleName()); // private int quantity;
for (VariableElement p : params)
out.printf(" public %s %s(%s v) { this.%s = v; return this; }%n",
builder, p.getSimpleName(), p.asType(), p.getSimpleName()); // public OrderBuilder quantity(int v) ...
String args = params.stream().map(p -> p.getSimpleName().toString()).collect(Collectors.joining(", "));
out.printf(" public %s build() { return new %s(%s); }%n", simple, simple, args); // new Order(id, quantity)
out.printf("}%n");
}
} catch (IOException ex) {
error(type, "could not write " + builder + ": " + ex.getMessage());
}
}
Step throughOne compilation with BuilderProcessor
javacBuilderProcessorFilerMessager
round 1: process(), Order is annotated
check kind, read constructor parameters
createSourceFile(com.acme.OrderBuilder, Order)
new source OrderBuilder.java
printMessage(ERROR, element) for bad uses
round 2: no annotated elements in OrderBuilder
compile Order and OrderBuilder together

7 messages in order. Play them, or step through them one at a time.

Notice that the generated class is in the same package as Order, so it can call a package-private constructor. The Generated annotation marks the file as generated, which tools such as coverage reports and linters use to skip it.

5Reporting Errors and Registering the Processor

Errors go through the Messager with the element they concern, so the compiler output points at the right line in the user's source, and the IDE underlines it. Throwing an exception from a processor instead gives the user a stack trace from inside javac, which is much harder to understand. Finally, we register the processor so javac can find it.

Java
private void error(Element e, String msg) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, e);
}
// Order.java:3: error: @GenerateBuilder needs a non-private constructor
// src/main/resources/META-INF/services/javax.annotation.processing.Processor
com.acme.BuilderProcessor

Consumers add the processor jar to their annotation processor path, for example Gradle's annotationProcessor configuration or Maven's annotationProcessorPaths. Recent JDKs do not run processors found only on the class path by default, so explicit configuration is the reliable way.

6Follow-up questions

How do you make the processor work with incremental compilation in Gradle?

Declare it in a resource file named META-INF/gradle/incremental.annotation.processors, with a line such as com.acme.BuilderProcessor,isolating. An isolating processor promises that each generated file depends only on one annotated element and what it references, and it must pass that element as the originating element to createSourceFile, as our write method does. Gradle can then recompile only the builders whose source class changed. Processors that need to see many elements together, such as one generating a registry of all annotated classes, declare themselves aggregating instead.

Why not read the fields instead of the constructor parameters?

Fields work for simple classes, but a constructor reflects how the class wants to be built, including validation and derived fields. Reading fields could produce a builder that sets values the class never accepts through its constructor. Records make this easy, because their canonical constructor matches their components exactly.

How would you test the processor?

Compile small sample sources in a test with the JDK's JavaCompiler API, or a helper library such as Google's compile-testing, and assert both the generated source and the diagnostics: that a valid class produces OrderBuilder and that an interface produces the expected error on the right element.

7Conclusion

In this answer, we outlined a processor that generates a Builder for classes annotated @GenerateBuilder. We extended AbstractProcessor, declared the supported annotation and returned SourceVersion.latestSupported(), iterated over roundEnv.getElementsAnnotatedWith, checked that each element is a class, read constructor parameters through ElementFilter and their TypeMirrors, and wrote OrderBuilder with the Filer, passing the original type as the originating element. We reported problems with Messager.printMessage on the offending element, returned false so other processors may read the annotation, registered the processor through META-INF/services, and declared it isolating for Gradle's incremental compilation.

What to say in the interviewAbout 80 seconds aloud

Open with

I would extend AbstractProcessor, annotate it with @SupportedAnnotationTypes for com.acme.GenerateBuilder, and override getSupportedSourceVersion to return SourceVersion.latestSupported, so it does not warn on every new Java release. The annotation itself only needs SOURCE retention and a TYPE target.

Then, if they want more

In process, I loop over roundEnv.getElementsAnnotatedWith(GenerateBuilder.class) and check that each element's kind is CLASS, because the TYPE target also allows interfaces and enums; for anything else I report an error.

For each class I find the non-private constructor with the most parameters using ElementFilter.constructorsIn, and read each parameter's name and TypeMirror, so the builder mirrors how the class wants to be built.

Then I call processingEnv.getFiler().createSourceFile with the builder's name in the same package, passing the original type element as the originating element, and write the class with a PrintWriter or, for anything bigger, JavaPoet: a field and a fluent setter per parameter, and a build method that calls the constructor.

Any problem goes through Messager.printMessage with Diagnostic.Kind.ERROR and the element, so the error points at the user's source line instead of a stack trace from javac. process returns false so I do not claim the annotation from other processors. I register it in META-INF/services/javax.annotation.processing.Processor, and for Gradle incremental builds I declare it isolating in META-INF/gradle/incremental.annotation.processors.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Outline an annotation processor that generates a Builder class for every class annotated...": https://scrivio-interview-library.netlify.app/java/annotations/f0ca26d34e/