使用 google-java-format 规范自己的代码

7,211 阅读2分钟

「这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战

一、简介:

google-java-format 是一个重新格式化Java源代码以符合 Google Java Style 的插件。

二、安装

google-java-format 可从插件库下载 也可以在IDE的File→Settings-->Plugins中下载。单击Marketplace选项卡,搜索google-java-format插件,然后单击Install按钮。 默认情况下,该插件将被禁用。要在当前项目中启用它,请转到File→Settings...→google-java-format Settings(或IntelliJ IDEA→Preferences...→Other Settings→google-java-format Settings在macOS上)并选中Enable google-java-format复选框(当您安装完毕重启idea以后,将显示通知,让你激活这个插件)。

三、使用

要在新项目中默认启用它,请在idea中的 File→Other Settings→Default Settings...中启用后,它将替换通常的Reformat Code操作,该操作可以从Code菜单中触发,也可以使用Ctrl-Alt-L(默认情况下)键盘快捷键触发。

不幸的是,此插件未处理导入顺序。要修复导入顺序,请下载 IntelliJ Java Google样式文件, 然后将其导入,File→Settings→Editor→Code Style.

四、 第三方集成

五、作为依赖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>
  <version>1.12.0</version>
</dependency>

Gradle

dependencies {
  implementation 'com.google.googlejavaformat:google-java-format:1.12.0'
}

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

String formattedSource = new Formatter().formatSource(sourceString);

or

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

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