“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”

I. Introduction:

Google-java-format is a plug-in that reformats Java source code to conform to Google Java Style.

Second, the installation

Google-java-format can be downloaded from the Plugins library or from File→Settings–>Plugins in the IDE. Click the Marketplace TAB, search for the Google-Java-Format plug-in, and click the Install button. By default, the plug-in is disabled. To enable it in your current project, go to File→Settings… → Google-Java-format Settings (IntelliJ IDEA→Preferences… →Other Settings→ Google-Java-format Settings on macOS) and check the Enable Google-Java-format check box (when you restart IDEA after installing, a notification will be displayed asking you to activate the plug-in).

Three, use,

To enable it by Default in a new project, go to File→Other Settings→Default Settings in idea… When enabled in, it replaces the usual Reformat Code action, which can be triggered from the Code menu or, by default, using ctrl-Alt-L keyboard shortcuts.

Unfortunately, this plug-in does not handle the import order. To fix the import order, download the IntelliJ Java Google Style File and then import it, File→Settings→Editor→Code Style.

Fourth, third-party integration

  • Integrate Gradle plug-ins

    • spotless
    • sherter/google-java-format-gradle-plugin
  • Integrate Apache Maven plugins

    • spotless
    • coveo/fmt-maven-plugin
    • talios/googleformatter-maven-plugin
    • Cosium/maven-git-code-format: A maven plugin that automatically deploys google-java-format as a pre-commit git hook.
  • Integrate SBT plug-in

    • sbt/sbt-java-formatter
  • maltzj/google-style-precommit-hook: A pre-commit (pre-commit.com) hook that will automatically run GJF whenever you commit code to your repository

  • Github Actions

    • googlejavaformat-action: Automatically format your Java files when you push on github

Use as a dependent JAR

The formatter can be used in software which generates java to output more legible java code. Just include the library in your maven/gradle/etc. configuration.

Maven

<dependency> <groupId>com.google.googlejavaformat</groupId> <artifactId>google-java-format</artifactId> The < version > 1.12.0 < / version > < / dependency >Copy the code

Gradle

Dependencies {implementation 'com. Google. Googlejavaformat: Google - Java - format: 1.12.0'}Copy the code

You can then use the formatter through the methods. E.g.formatSource

String formattedSource = new Formatter().formatSource(sourceString);
Copy the code

or

CharSource source = ...
CharSink output = ...
new Formatter().formatSource(source, output);
Copy the code

Your starting point should be the instance methods of .com.google.googlejavaformat.java.Formatter