google-java-format is a program that reformats Java source code to comply with
Google Java Style.
Download the formatter and run it with:
java -jar /path/to/google-java-format-${GJF_VERSION?}-all-deps.jar <options> [files...]
Note that it uses the jdk.compiler module to parse the Java source code. The
java binary version used must therefore be from a JDK (not JRE) with a version
equal to or newer than the Java language version of the files being formatted.
The minimum Java version can be found in
pom.xml
(currently Java 21). An alternative is to use the available GraalVM based native
binaries instead.
The formatter can act on whole files, on limited lines (--lines), on specific
offsets (--offset), passing through to standard-out (default) or altered
in-place (--replace).
Option --help will print full usage details; including built-in documentation
about other flags, such as --aosp, --fix-imports-only,
--skip-sorting-imports, --skip-removing-unused-import,
--skip-reflowing-long-strings, --skip-javadoc-formatting, or the --dry-run
and --set-exit-if-changed.
Using @<filename> reads options and filenames from a file, instead of
arguments.
To reformat changed lines in a specific patch, use
google-java-format-diff.py.
Note: There is no configurability as to the formatter's algorithm for formatting. This is a deliberate design decision to unify our code formatting on a single format.
A
google-java-format IntelliJ plugin
is available from the plugin repository. To install it, go to your IDE's
settings and select the Plugins category. Click the Marketplace tab, search
for the google-java-format plugin, and click the Install button.
The plugin will be disabled by default. To enable, open the Project settings, then click "google-java-format Settings" and check the "Enable google-java-format" checkbox.
To enable it by default in new projects, open the default settings for new projects