A custom Checkstyle rule that prohibits the use of annotations on private methods. This helps enforce code quality by ensuring that annotations are not mistakenly applied to methods that are not accessible outside their class.
- Fails Checkstyle if a private method is annotated.
- Easily pluggable into your existing Checkstyle configuration.
Extend yours gradle checkstyle plugin with this custom rule, required updates in build.gradle
plugins {
// ...
id 'checkstyle'
// ...
}
dependencies {
// add dependencies to checkstyle plugin context
// add checkstyle tools
checkstyle "com.puppycrawl.tools:checkstyle:${checkstyle.toolVersion}"
// add new custom rule
checkstyle 'dev.jora.checkstyle:checkstyle-no-private-method-annotation-rule:1.0.0'
}
checkstyle {
// yours checkstyle configuration here
}-
Update your Checkstyle configuration (XML):
Add the custom rule to your
checkstyle.xml:<module name="Checker"> ... <module name="TreeWalker"> ... <module name="NoPrivateAnnotatedMethodCheck"> <property name="severity" value="error"/> <property name="forbiddenAnnotations" value="MyAnnotation"/> <property name="forbiddenAnnotations" value="MyAnnotation2"/> <property name="forbiddenAnnotations" value="Transactional"/> </module> </module> ... </module>
-
Run Checkstyle:
With Gradle:
gradle checkstyleMain
Violated code example
public class Example {
@Transactional // <-- This will trigger a Checkstyle violation
private void doSomething() {
}
public void validMethod() {
}
}Log output example
[ERROR] Example.java:2:5: Annotation 'Transactional' is not allowed on private methods [NoPrivateAnnotatedMethod]
The Apache License, Version 2.0