Alexandros Milaios
Alexandros Milaios

Reputation: 23

Block Public Access to Inner Interfaces/Classes with CheckStyle

Is there a way to update checkstyle setup to allow only package private inner interfaces or classes? For example


public class A {
 ...
 public interface B { // should flag it as error
  ..
 }
}

public class A {
 ...
 interface B { // valid syntax
  ..
 }
}

Upvotes: 2

Views: 115

Answers (1)

Nick Mancuso
Nick Mancuso

Reputation: 191

You can use MatchXPath for this:


<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
        "http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">

<module name="Checker">
    <property name="charset" value="UTF-8"/>
    <property name="haltOnException" value="true"/>
    <property name="severity" value="error"/>

    <module name="TreeWalker">
        <module name="MatchXpath">
            <property name="query" value="/CLASS_DEF/OBJBLOCK/(CLASS_DEF | INTERFACE_DEF)/MODIFIERS[(*)]"/>
            <message key="matchxpath.match"
                     value="Only package private inner interfaces or classes are allowed."/>
        </module>
    </module>
</module>



public class A {

    public interface B { // violation

    }

    public class C { // violation

    }

    public enum D { // ok, enum not specified in config

    }

    class E { // ok, no modifier

    }

    interface F { ok, no modifier

    }

    private class G { // violation

    }

    private interface H { // violation

    }
}



➜  src java -jar checkstyle-8.41-all.jar -c config.xml A.java
Starting audit...
[ERROR] A.java:3:5: Only package private inner interfaces or classes are allowed. [MatchXpath]
[ERROR] A.java:7:5: Only package private inner interfaces or classes are allowed. [MatchXpath]
[ERROR] A.java:23:5: Only package private inner interfaces or classes are allowed. [MatchXpath]
[ERROR] A.java:27:5: Only package private inner interfaces or classes are allowed. [MatchXpath]
Audit done.
Checkstyle ends with 4 errors.


Upvotes: 2

Related Questions