Generating Source Files with Filer
What You'll Learn
You'll learn how to use the Filer interface to programmatically create new Java source files during the compilation process.
Why Generate Source Files?
Annotation processors don't just read code—they can write new code too. The Filer interface is your gateway to creating .java files that will be compiled alongside your original source code. Think of it as a code-writing robot that operates during compilation.
The Filer Interface
During annotation processing, you access Filer through the ProcessingEnvironment:
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
Filer filer = processingEnv.getFiler();
}
Creating Source Files
The Filer provides createSourceFile() to generate new .java files. You specify the fully-qualified class name and get back a JavaFileObject that you write to:
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
try {
JavaFileObject sourceFile = processingEnv.getFiler()
.createSourceFile("com.example.GeneratedClass");
try (Writer writer = sourceFile.openWriter()) {
writer.write("package com.example;\n\n");
writer.write("public class GeneratedClass {\n");
writer.write(" public String getMessage() {\n");
writer.write(" return \"Generated!\";\n");
writer.write(" }\n");
writer.write("}\n");
}
} catch (IOException e) {
// Handle error
}
return true;
}
This creates a fully-functional GeneratedClass.java file that gets compiled automatically.
Important Considerations
- Each file can only be created once per compilation
- Generated files appear in the build output, not your source directory
- Always close writers properly (use try-with-resources)
- The processor must specify which annotations trigger generation
Key Takeaway: The Filer interface lets annotation processors generate new Java source files during compilation, enabling powerful code generation patterns like builders, adapters, and boilerplate reduction.