How can a consistent Java code format be enforced?

You could use the Google Java Format, which has plugins for the aforementioned IDEs (IntelliJ IDEA, Eclipse), it provides integrations with tools such as Maven, Gradle, or SBT, and provides means to run the formatter as pre-commit hook or when pushing the code to Github with Github actions.

In their README they also mention the imports issue and how to fix it for IntelliJ IDEA, and more insights are provided e.g.: on how to handle it on Spotless Gradle plugin, when using the Maven Spotless plugin, or for Github actions.

A drawback for your specific case may be that the tool enforces the Google Java style guide, which was praised and recommended by the Oracle Java team as described in the Oracle Java magazine. It also provides the option to use the AOSP code style.

Below a snippet for spotless Gradle configuration, considering imports ordering:

spotless {
    java {
        importOrder() // standard import order
        importOrder('java', 'javax', 'com.acme', '') // or importOrderFile
        // You probably want an empty string at the end - all of the
        // imports you didn't specify explicitly will go there.

        removeUnusedImports()

        googleJavaFormat() // has its own section below
        eclipse()          // has its own section below
        prettier()         // has its own section below
        clangFormat()      // has its own section below

        licenseHeader '/* (C) $YEAR */' // or licenseHeaderFile
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)