Search code examples
javaannotationsguicecheckstylepmd

How to enforce constructor injection with checkstyle or PMD?


I'd like to enforce constructor injection in a GWT project with uses the Guice annotation com.google.inject.Inject which is either place on fields for field injection and on constructors for constructor injection.

The project already uses checkstyle and PMD.

Afaik I could simply enforce constructor injection by disallowing the annotation on fields, however I find no checkstyle module or PMD rule to do this. I'm sure that I'm missing something because it seems like an everyday task for a static code analysis tool.


Solution

  • This sounds like a good candidate for Checkstyle's MatchXpath check. You could add two modules to your configuration like so:

    <module name="MatchXpath">
      <property name="query" value="//VARIABLE_DEF/MODIFIERS/ANNOTATION/IDENT[@text='Inject']"/>
      <message key="matchxpath.match"
                         value="Inject annotation only allowed on constructors."/>
    </module>
    
    <module name="MatchXpath">
      <property name="query" value="//METHOD_DEF/MODIFIERS/ANNOTATION[./IDENT[@text='Inject']]"/>
      <message key="matchxpath.match"
                         value="Inject annotation only allowed on constructors."/>
    </module>
    
    

    Example java file:

    public class Communication {
        @Inject @Named("SMSComms")
        CommunicationMode smsComms;
    
        @Inject
        public void setEmailCommunicator(@Named("EmailComms") CommunicationMode emailComms) {
            this.emailComms = emailComms;
        }
    
        @Inject
        public Communication(@Named("IMComms") CommunicationMode imComms) {
            this.imComms = imComms;
        }
    }
    
    

    Result:

    
    ➜  src java -jar checkstyle-8.40-all.jar -c config.xml Communication.java
    Starting audit...
    [ERROR] src/Communication.java:2:6: Inject annotation only allowed on constructors. [MatchXpath]
    [ERROR] src/Communication.java:5:5: Inject annotation only allowed on constructors. [MatchXpath]
    Audit done.
    Checkstyle ends with 2 errors.