How to Use Checkstyle's API for Custom Tooling: A Complete Guide to Programmatic Analysis
Use ConfigurationLoader to parse your XML config, instantiate Checker as the root module, register AuditListener implementations for results, and call process(List<File>) to run the audit.
Checkstyle's architecture exposes a clean, embeddable API through the com.puppycrawl.tools.checkstyle.api package. Whether you're building an IDE plugin, CI integration, or standalone analysis tool, you can drive Checkstyle programmatically without shelling out to the command line. This guide walks through the exact sequence of API calls, key classes, and working code examples drawn from the checkstyle/checkstyle source.
Core Architecture: The Five Layers
Understanding Checkstyle's modular design helps you hook into the right extension points.
| Layer | Responsibility | Key Types |
|---|---|---|
| Root module | Orchestrates the entire audit lifecycle | Checker |
| Configuration | Parses XML into module descriptions | ConfigurationLoader |
| File-set checks | Processes collections of files | FileSetCheck interface, TreeWalker |
| Individual checks | Analyze specific AST constructs | AbstractCheck subclasses |
| Listeners | Receive and handle audit events | AuditListener implementations |
Every layer is exposed through public API classes, making it possible to substitute custom implementations at any point.
Step-by-Step: Running Checkstyle Programmatically
Step 1: Load the Configuration
The ConfigurationLoader.loadConfiguration() method parses your Checkstyle XML file into a Configuration object. This object describes which modules to instantiate and their property values.
import com.puppycrawl.tools.checkstyle.ConfigurationLoader;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.properties.PropertyResolver;
String configPath = "config/checkstyle.xml";
PropertyResolver resolver = PropertyResolver.EMPTY_RESOLVER;
Configuration config = ConfigurationLoader.loadConfiguration(
configPath,
resolver,
ConfigurationLoader.IgnoredModulesOptions.OMIT
);
The PropertyResolver handles property substitution (like ${basedir}). Use OMIT to skip ignored modules or EXECUTE to include them.
Step 2: Create and Configure the Checker
Checker is the root module that implements MessageDispatcher and RootModule. It controls the audit lifecycle from start to finish.
import com.puppycrawl.tools.checkstyle.Checker;
Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(config);
The classloader is critical when your custom checks reside outside Checkstyle's core JAR. The configure(Configuration) method— inherited from AbstractAutomaticBean—injects all configured properties into the Checker and its child modules.
Step 3: Register Audit Listeners
Listeners implement AuditListener to receive events at audit boundaries and for each violation:
auditStarted(AuditEvent)/auditFinished(AuditEvent)— entire runfileStarted(AuditEvent)/fileFinished(AuditEvent)— per fileaddError(AuditEvent)— violation detectedaddException(AuditEvent, Throwable)— processing error
checker.addListener(new AuditListener() {
@Override
public void addError(AuditEvent event) {
System.out.printf("%s:%d: %s%n",
event.getFileName(),
event.getLine(),
event.getMessage());
}
@Override public void auditStarted(AuditEvent e) {}
@Override public void fileStarted(AuditEvent e) {}
@Override public void fileFinished(AuditEvent e) {}
@Override public void auditFinished(AuditEvent e) {}
@Override public void addException(AuditEvent e, Throwable t) {}
});
Step 4: Process Files
The process(List<File>) method runs the full audit and returns the total error count.
import java.io.File;
import java.util.List;
List<File> files = List.of(
new File("src/main/java/com/example/Service.java"),
new File("src/main/java/com/example/Controller.java")
);
int errorCount = checker.process(files);
Internally, Checker iterates through all configured FileSetCheck modules. For each file, it creates a FileText representation and delegates to checks.
Step 5: Clean Up
Always call destroy() to release resources and flush any configured cache:
checker.destroy();
Complete Working Example
This self-contained class demonstrates the full API integration with proper error handling and a reusable listener.
package com.example.checkstyle;
import com.puppycrawl.tools.checkstyle.Checker;
import com.puppycrawl.tools.checkstyle.ConfigurationLoader;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.properties.PropertyResolver;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ProgrammaticCheckstyle {
/** Collector that gathers violations for programmatic access. */
public static class ViolationCollector implements AuditListener {
private final List<Violation> violations = new ArrayList<>();
public record Violation(String file, int line, int column,
String message, String source) {}
@Override
public void addError(AuditEvent event) {
violations.add(new Violation(
event.getFileName(),
event.getLine(),
event.getColumn(),
event.getMessage(),
event.getSourceName()
));
}
public List<Violation> getViolations() {
return List.copyOf(violations);
}
// Other AuditListener methods (no-ops for this use case)
@Override public void auditStarted(AuditEvent e) {}
@Override public void auditFinished(AuditEvent e) {}
@Override public void fileStarted(AuditEvent e) {}
@Override public void fileFinished(AuditEvent e) {}
@Override public void addException(AuditEvent e, Throwable t) {}
}
public static List<ViolationCollector.Violation> analyze(
String configPath,
List<File> sourceFiles) throws Exception {
// Load configuration
Configuration config = ConfigurationLoader.loadConfiguration(
configPath,
PropertyResolver.EMPTY_RESOLVER,
ConfigurationLoader.IgnoredModulesOptions.OMIT
);
// Set up checker
Checker checker = new Checker();
checker.setModuleClassLoader(
ProgrammaticCheckstyle.class.getClassLoader()
);
checker.configure(config);
// Attach collector
ViolationCollector collector = new ViolationCollector();
checker.addListener(collector);
// Run analysis
try {
checker.process(sourceFiles);
} finally {
checker.destroy();
}
return collector.getViolations();
}
public static void main(String[] args) throws Exception {
List<ViolationCollector.Violation> results = analyze(
"google_checks.xml",
List.of(new File("src/main/java/Example.java"))
);
results.forEach(v -> System.out.printf(
"%s:%d:%d: %s%n", v.file(), v.line(), v.column(), v.message()
));
}
}
Extending the API: Custom Checks and Filters
Writing Custom Checks
Extend AbstractCheck to implement new analysis rules. The base class provides:
getAcceptableTokens(),getDefaultTokens(),getRequiredTokens()— declare AST node typesvisitToken(DetailAST),leaveToken(DetailAST)— handle nodes during tree traversallog(int line, String key, Object... args)— report violations
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class MethodLengthCheck extends AbstractCheck {
private int max = 100; // Configurable property
public void setMax(int max) {
this.max = max;
}
@Override
public int[] getDefaultTokens() {
return new int[]{TokenTypes.METHOD_DEF};
}
@Override
public void visitToken(DetailAST ast) {
int length = countLines(ast);
if (length > max) {
log(ast.getLineNo(), "method.length", max, length);
}
}
private int countLines(DetailAST methodDef) {
// Implementation using DetailAST navigation
return 0;
}
}
Custom Filters
Implement Filter to suppress violations based on custom logic—useful for baseline integration or noise reduction.
import com.puppycrawl.tools.checkstyle.api.Filter;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
public class BaselineFilter implements Filter {
@Override
public boolean accept(AuditEvent event) {
// Return false to suppress this violation
return !isKnownViolation(event);
}
private boolean isKnownViolation(AuditEvent event) {
// Check against existing baseline
return false;
}
}
Register filters in your configuration XML or programmatically via the Checker's filter chain.
Performance Considerations
- Reuse
Checkerinstances: Creating and configuring aCheckerhas overhead. Reuse across multiple file batches when possible. - Control
FileTextencoding: Set thecharsetproperty in configuration to avoid charset detection overhead. - Enable caching: Configure a
cacheFileproperty to skip unchanged files in subsequent runs.
Summary
ConfigurationLoaderparses XML configurations intoConfigurationobjects for programmatic useCheckerserves as the root module that orchestrates the entire audit lifecycleAuditListenerimplementations receive all audit events and violations for custom processingprocess(List<File>)executes the analysis and returns the total error countAbstractCheckprovides the extension point for implementing custom analysis rules- Proper cleanup via
destroy()ensures resources are released and caches are persisted
Frequently Asked Questions
What is the minimum code needed to run Checkstyle programmatically?
At minimum, you need four API calls: ConfigurationLoader.loadConfiguration() to parse config, new Checker() to create the engine, checker.configure(config) to apply settings, and checker.process(files) to run analysis. Add a listener to capture results. Always call checker.destroy() when finished.
How do I use a custom check class with the programmatic API?
Ensure your check's JAR is available to the classloader you pass to checker.setModuleClassLoader(). Reference the custom check by fully-qualified class name in your configuration XML, just as you would for built-in checks.
Can I run Checkstyle without a configuration file?
Yes, but you must construct the Configuration object programmatically. Create a DefaultConfiguration instance, add child configurations for each module with addChild(), and set properties via addAttribute(). This bypasses ConfigurationLoader entirely.
What's the difference between FileSetCheck and individual checks?
FileSetCheck operates on an entire file or file set—TreeWalker is the primary example, converting files to ASTs. Individual checks (extending AbstractCheck) analyze specific AST nodes within that tree. The Checker coordinates both layers.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →