google-java-format + Spotless Java Formatter Docs | Web Formatter Blog

google-java-format + Spotless Java Formatter Docs
Reference documentation for google-java-format and Spotless Java code formatters to maintain consistent code style across your Java projects.
Introduction to Java Formatting
Java's syntax, while structured and readable, can be formatted in various ways. Consistent formatting is crucial for code readability, maintainability, and collaboration in team environments. This guide explores two powerful tools for Java code formatting: google-java-format and Spotless.
Both tools help enforce consistent code style across your Java projects, but they approach the task differently. google-java-format is focused specifically on Java code formatting with opinionated style rules, while Spotless is a more general-purpose formatting tool that can be configured to use google-java-format and other formatters.
Why Format Your Java Code?
Consistent code formatting offers numerous benefits beyond just aesthetics:
- Improved readability: Consistently formatted code is easier to scan and understand
- Reduced cognitive load: Developers can focus on logic rather than deciphering formatting variations
- Easier onboarding: New team members can quickly adapt to your codebase's style
- Faster code reviews: Reviewers can focus on substance rather than style
- Reduced merge conflicts: Consistent formatting minimizes unnecessary whitespace changes
- Enforced best practices: Many formatting rules align with Java community standards
While Java developers have historically had different formatting preferences, tools like google-java-format and Spotless help teams standardize on a consistent style, reducing debates about formatting and allowing developers to focus on writing quality code.
Understanding google-java-format
google-java-format is an opinionated Java code formatter that follows Google's Java Style Guide. Created by Google, it reformats Java source code to comply with Google's style specifications, with very few configurable options.
Key features of google-java-format include:
- Deterministic formatting: The same input code always produces the same formatted output
- Opinionated style: Based on Google's Java Style Guide with minimal configuration options
- Speed: Efficiently formats large codebases
- IDE integration: Plugins available for IntelliJ IDEA, Eclipse, and other editors
- Command-line interface: Can be run from the terminal or integrated into build processes
google-java-format is particularly useful for teams that want to adopt a well-established style guide without spending time debating formatting rules.
Understanding Spotless
Spotless is a versatile code formatter created by Diffplug that supports multiple languages and formatting engines. For Java, it can be configured to use google-java-format, Eclipse's formatter, or other formatting tools.
Key features of Spotless include:
- Multi-language support: Beyond Java, it handles Kotlin, Scala, JavaScript, and more
- Flexible configuration: Can be tailored to your team's specific needs
- Build tool integration: Plugins for Gradle and Maven
- Incremental formatting: Can format only changed files for faster builds
- License header management: Can add or update license headers in source files
- Import ordering: Can organize and sort import statements
Spotless is ideal for projects that need more flexibility in their formatting rules or teams working with multiple languages that want a unified formatting solution.
Installation
Installing google-java-format
There are several ways to install google-java-format:
As a standalone JAR:
# Download the latest version
curl -L https://github.com/google/google-java-format/releases/download/v1.15.0/google-java-format-1.15.0-all-deps.jar -o google-java-format.jar
# Run the formatter
java -jar google-java-format.jar --replace path/to/file.java
With Maven:
com.coveo
fmt-maven-plugin
2.13
format
With Gradle:
plugins {
id 'java'
id 'com.github.sherter.google-java-format' version '0.9'
}
googleJavaFormat {
toolVersion = '1.15.0'
}
Installing Spotless
Spotless is typically integrated into your build system:
With Gradle:
plugins {
id 'com.diffplug.spotless' version '6.18.0'
}
spotless {
java {
// Use google-java-format
googleJavaFormat('1.15.0')
// Or use Eclipse's formatter
// eclipse().configFile('eclipse-formatter.xml')
}
}
With Maven:
com.diffplug.spotless
spotless-maven-plugin
2.36.0
1.15.0
check
Basic Usage
Using google-java-format
From the command line:
# Format a single file
java -jar google-java-format.jar --replace path/to/file.java
# Format multiple files
java -jar google-java-format.jar --replace path/to/file1.java path/to/file2.java
# Format all Java files in a directory
find path/to/directory -name "*.java" | xargs java -jar google-java-format.jar --replace
With Maven:
# Format all Java files
mvn fmt:format
With Gradle:
# Format all Java files
./gradlew googleJavaFormat
Using Spotless
With Gradle:
# Check if files are formatted correctly
./gradlew spotlessCheck
# Apply formatting to all files
./gradlew spotlessApply
With Maven:
# Check if files are formatted correctly
mvn spotless:check
# Apply formatting to all files
mvn spotless:apply
Configuration
google-java-format Configuration
google-java-format is intentionally minimalistic in its configuration options. The main options include:
# Use Google's Java style (default)
java -jar google-java-format.jar --aosp=false --replace file.java
# Use Android Open Source Project style
java -jar google-java-format.jar --aosp=true --replace file.java
# Format only selected lines (1-10, 15, 20-25)
java -jar google-java-format.jar --lines=1-10,15,20-25 --replace file.java
When using the Maven or Gradle plugins, you can configure these options in your build files:
// Gradle
googleJavaFormat {
toolVersion = '1.15.0'
options = ['--aosp']
}
com.coveo
fmt-maven-plugin
2.13
Spotless Configuration
Spotless offers much more extensive configuration options:
// Gradle
spotless {
java {
// Use google-java-format
googleJavaFormat('1.15.0').aosp()
// Remove unused imports
removeUnusedImports()
// Sort imports
importOrder('java', 'javax', 'org', 'com', '')
// Add license header
licenseHeader '/* Copyright $YEAR */'
// Custom rules
custom 'no trailing whitespace', { it.replaceAll('[ \\t]+$', '') }
// Exclude generated files
targetExclude 'src/generated/**/*.java'
}
}
com.diffplug.spotless
spotless-maven-plugin
2.36.0
1.15.0
java,javax,org,com,
/* Copyright $YEAR */
src/generated/**/*.java
Code Examples
Java Formatting Examples
The formatted code shows several improvements:
-
Consistent spacing around operators (
=
,{" "}+
, etc.) - Consistent indentation (2 spaces per level for Google style)
-
Proper spacing in control structures (
for
,{" "}if
) - Consistent brace placement
- Proper line breaks for improved readability
- Consistent spacing after commas in parameter lists
Editor Integration
Integrating formatters with your IDE provides real-time feedback and automatic formatting.
IntelliJ IDEA
For google-java-format in IntelliJ IDEA:
- Install the "google-java-format" plugin from the JetBrains Marketplace
- Go to Settings/Preferences → Other Settings → google-java-format Settings
- Enable "Enable google-java-format" and select your preferred style
- Optionally, enable "Format on save"
For Spotless in IntelliJ IDEA:
- Install the "Spotless" plugin from the JetBrains Marketplace
- Go to Settings/Preferences → Tools → Spotless
- Configure the plugin to run on save or with a keyboard shortcut
Eclipse
For google-java-format in Eclipse:
- Download the google-java-format Eclipse plugin JAR
- Place it in the Eclipse "dropins" folder
- Restart Eclipse
- Go to Window → Preferences → Java → Code Style → Formatter
- Select "Google Java Format" as the active profile
For Spotless in Eclipse, you can use the Buildship Gradle integration or M2Eclipse for Maven projects to run Spotless tasks.
Visual Studio Code
For google-java-format in VS Code:
- Install the "Java Extension Pack" from the marketplace
- Install the "Google Java Format" extension
- Configure settings.json to use google-java-format
{
"java.format.settings.url": "https://raw.githubusercontent.com/google/styleguide/gh-pages/eclipse-java-google-style.xml",
"editor.formatOnSave": true,
"java.format.enabled": true
}
For Spotless in VS Code, you can use the Gradle or Maven extensions to run Spotless tasks.
Automating Formatting
Git Pre-commit Hooks
You can use pre-commit hooks to ensure all committed code is properly formatted:
#!/bin/sh
# .git/hooks/pre-commit
# For google-java-format
files=$(git diff --cached --name-only --diff-filter=ACM | grep "*.java$")
if [ -n "$files" ]; then
java -jar /path/to/google-java-format.jar --replace $files
git add $files
fi
# For Spotless
./gradlew spotlessApply
git add $(git diff --cached --name-only --diff-filter=ACM)
Alternatively, you can use tools like Husky or pre-commit to manage your hooks more easily.
CI/CD Integration
Add formatting checks to your CI pipeline to catch issues early. Example for GitHub Actions:
name: Java Formatting
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: gradle
# For google-java-format
- name: Check formatting with google-java-format
run: |
curl -L https://github.com/google/google-java-format/releases/download/v1.15.0/google-java-format-1.15.0-all-deps.jar -o google-java-format.jar
java -jar google-java-format.jar --dry-run --set-exit-if-changed $(find . -name "*.java")
# For Spotless
- name: Check formatting with Spotless
run: ./gradlew spotlessCheck
Best Practices
To get the most out of your Java formatting tools:
- Format early and often: Integrate formatting into your development workflow from the start
- Automate formatting: Use IDE plugins, git hooks, and CI checks to enforce formatting
- Format entire files: Avoid formatting only parts of files to maintain consistency
- Version control your configuration: Keep formatting settings in version control
- Agree on a style: Have your team agree on a formatting style before implementing it
- Format gradually: For existing projects, consider formatting files as they're modified
- Separate formatting commits: Keep formatting changes separate from functional changes
Troubleshooting Common Issues
When working with Java formatters, you might encounter these common issues:
Issue | Solution |
---|---|
Formatter fails on valid Java code | Ensure you're using the latest version of the formatter |
Formatting breaks comments | Check if your comments contain special formatting that might be affected |
Conflicts with IDE formatting | Disable IDE's built-in formatter or configure it to match your chosen formatter |
Build failures in CI | Ensure all developers format locally before pushing or set up pre-commit hooks |
Performance issues with large codebases | Use incremental formatting or format only changed files |
Conclusion
Consistent code formatting significantly improves code readability, maintainability, and collaboration in Java projects. Both google-java-format and Spotless offer powerful solutions for enforcing consistent style across your codebase.
google-java-format is ideal for teams that want a simple, opinionated formatter with minimal configuration, while Spotless offers more flexibility and additional features like license header management and import ordering.
By integrating these tools into your development workflow through IDE plugins, git hooks, and CI/CD pipelines, you can ensure consistent formatting across your entire team and focus on what matters most: writing high-quality Java code.