I'm looking for a Java formatter that a team can run locally, including in WSL, and check in CI without depending on an IDE. What options are worth considering, especially for newer Java syntax and lambda formatting?
What Java formatter works well from the command line and in CI?
Answers
Google Java Format is a solid starting point. You can run it from the command line or use it through Spotless in your build, then have CI check that formatting has been applied.
Its style is fairly opinionated, including two-space indentation, so try it on some real code before committing the whole team. Lambda formatting is a matter of taste, and support for newer syntax is worth checking against the version of the formatter you plan to use.
Reply to this answer
For teams that want more control, Spotless with the Eclipse formatter is worth a look. Spotless handles the build integration, while the Eclipse configuration lets you tune the formatting rules.
You can also package a shared configuration as a dependency if you want several projects to follow the same rules. That takes more setup than adopting an opinionated formatter, but it avoids having every project maintain its own copy.
Reply to this answer
Palantir Java Format is another option, though I wouldn't assume it's either abandoned or a safe fit without checking. There are differing views on its maintenance and how quickly it handles new Java syntax.
Check its current releases against the language features your team uses, then run it on a representative sample. A formatter that lags your Java upgrade can become a CI headache.
Reply to this answer
Netflix jfmt is another formatter to investigate if the usual choices don't suit the team. Compare its output and current Java syntax support with your requirements before adopting it.
Reply to this answer
I'd optimize for consistent diffs rather than a perfect layout. Pick a formatter the team can tolerate, test it on the awkward lambda-heavy files, and make the same check available locally and in CI.
Skipping a formatter is an option too, but then the team has to settle style differences some other way.
Reply to this answer
Add your answer
Answers are reviewed before publication.
_s85+radarcradle.2:
There's also a command-line tool called jfmt that uses the Eclipse formatter and is compiled with Graal for quicker startup.