java - 如何自动格式化Java代码

标签 java git code-formatting

注意:在投票结束这个问题之前,请注意我不是在征求任何关于编码指南的意见;我只想帮助自动执行任务。


我有一个新同事,他喜欢到处都是异国情调的代码指南:

obj.method( a, b );

@JoinColumn( name = "LANGUAGE_ID", referencedColumnName = "ID" )
@ManyToOne( optional = false, fetch = EAGER )

空格..到处都是空格!

当你有链式代码时,这会变得很难阅读。

adapters.stream().filter( adapter -> isValidCRM( adapter.getId(), crmIds ) )
            .forEach( crmAdapter -> futures.add( CompletableFuture
                    .supplyAsync( () -> crmAdapter.getPerson( id ), ec ).exceptionally( throwable -> {
                        LOGGER.error( throwable.getMessage() );
                        return Response.builder().error( throwable ).build();
                    } ) ) );

我厌倦了和他争论,我不想那样写代码,所以我在 pre-commit git hooks 和 Jalopy 上做了一些谷歌搜索......但找不到任何有用的东西。 Jalopy 看起来很老(Java 1.5)。

基本上,我需要根据他的奇特指南(他配置了 tt_checkstyle.xml)在推送时自动格式化代码。在 pull 上,我不介意根据 Java 编码指南手动重新格式化代码。

我们使用的是 Java 1.8,我使用的是 NetBeans。我们使用 git。

有任何帮助(或任何替代方法来处理这个问题)吗?谢谢

最佳答案

您可以在服务器和本地使用 git hook 或设置本地过滤器(涂抹/清洁)

Git 钩子(Hook)

阅读官方文档以获取完整引用。


涂抹/清洁

阅读所有相关信息并在此处进行设置:
https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes

It turns out that you can write your own filters for doing substitutions in files on commit/checkout.

These are called clean and smudge filters.

In the .gitattributes file, you can set a filter for particular paths and then set up scripts that will process files just before they’re checked out (“smudge”, see Figure 8-2) and just before they’re staged (“clean”, see Figure 8-3).

These filters can be set to do all sorts of fun things.

enter image description here

关于java - 如何自动格式化Java代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36861425/

相关文章:

java - 通过键盘输入在 Canvas 上绘制文本

java - Android 中的地址建议

git - 检查分支是否已经 merge 到远程的 master 或 dev 分支中

c++ - Visual Studio C++ "Automatically format completed block on }"

git - 重建 git 历史记录的脚本,对每个版本应用代码清理

java - 有没有一种为模式构建 Java 正则表达式的动态方法?

GIT 从裸仓库中 pull

php - 可以在同一个 git 存储库中存储两种不同类型的代码吗?

c++ - 转换非常长的 C++ 字符串文字以满足最大行长度策略

java - 如何在单击 "exit"MenuItem() 时关闭窗口?