Search code examples
javastatic-analysischeckstyle

Checkstyle disallow specific enum constant


Is there a way to use checkstyle to disallow use of a specific enum value (other than trying to catch it with a regex)?

I would like to prevent the usage of javax.persistence.CascadeType.ALL, but can only seem to find options to prevent using the entire javax.persistence.CascadeType enum.


Solution

  • it is not so easy, but there a few ways (or workarounds?)

    1. You can use MatchXPathCheck to report violation on any usage of CascadeType.ALL. Config will look like
    <!-- under TreeWalker -->
    <module name="MatchXpath">
        <property name="query" value="//DOT[count(./IDENT) = 2 and ./*[1][@text = 'CascadeType'] and ./*[2][@text = 'ALL']]"/>
        <message key="matchxpath.match"
                 value="Do not use Cascade.ALL"/>
    </module>
    

    it will report violations on any usages of CascadeType.ALL, excluding imports. But it will not work in case you use static import and constant directly, e.g.

    import static javax.persistence.CascadeType.ALL;
    
    Object a = ALL; // we wont catch it
    
    1. Other way is other xpath, but to forbid to use ALL
    <!-- under TreeWalker -->
    <module name="MatchXpath">
        <property name="query" value="//IDENT[@text = 'ALL']"/>
        <message key="matchxpath.match"
            value="Do not use CascadeType.ALL"/>
    </module>
    

    this will catch all usages (imports too), but can produce false positives if you have some other constants named ALL, because here we do not specify its type.

    1. To forbid static import of this, you can use IllegalImportCheck. It will report violations on cases like
    import static javax.persistence.CascadeType.ALL;
    

    But it wont work in case there is a star import.

    You can also try to combine these approaches or create better xpath, since those above are just a sketch.