javacode-formattingspotless

How can I force the 'this' keyword on local fields and methods with the Spotless Java code formatter?


I want to enforce the use of the 'this' keyword using Spotless. For example: getTowerData().recordMap would be this.getTowerData().recordMap.

I'm running Spotless with Gradle with the current configuration:

spotless {
    java {
        importOrder('emu.grasscutter', '', 'java', 'javax', '\\#java', '\\#')
        googleJavaFormat('1.15.0')
        formatAnnotations()
        endWithNewline()
        indentWithTabs(2); indentWithSpaces(4)
        toggleOffOn()
    }
}

Currently, I've tried using:

custom('this', {
    // Force use of 'this.' keyword
    it.replaceAll('^\\s*(?!public|private|protected)(?!class|interface|enum|@interface)\\b(?!return)\\w+\\b', 'this.$0')
})

but this results in:

Step 'google-java-format' found problem in 'src\main\java\emu\grasscutter\auth\AuthenticationSystem.java':
null
java.lang.reflect.InvocationTargetException
Caused by: com.google.googlejavaformat.java.FormatterException: 1:2: error: class, interface, enum, or record expected

Solution

  • In a comment by devatherock, the checkstyle plugin for Gradle was mentioned and solves this exact issue. While it isn't specifically Spotless, it's the best solution to this problem.