4

Is there any PMD or Checkstyle rule available that could help me to prohibit usage of some certain classes in Java code?

In my case I'd like to ban all of the following in all possible contexts:

  • org.apache.commons.lang3.CharEncoding
  • org.apache.commons.lang.CharEncoding
  • org.apache.commons.codec.CharEncoding

I've found IllegalImport check, but it's about packages, not particular classes.

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
  • Perhaps this can help you ... http://stackoverflow.com/questions/8416870/checkstyle-rule-to-prevent-invocation-of-some-methods-and-constructors – Em Ae Feb 03 '16 at 18:24
  • @EmAe but the above is about certain methods or constructors, while my question is about classes – Michal Kordas Feb 03 '16 at 18:28
  • I know but what i was pointing at that I am not aware of any such restrictions so perhaps you might have to write something on your own just the way this post hints for writing on your own for methods. – Em Ae Feb 03 '16 at 18:29
  • @EmAe sure, if there is nothing ready to use I'm gonna write my own check – Michal Kordas Feb 03 '16 at 18:41
  • I don't speak xml, but look at this `checkstyle/config/import-control.xml` at https://github.com/checkstyle/checkstyle/blob/master/config/import-control.xml – Marichyasana Feb 03 '16 at 20:22
  • 1
    Interesting that you would ask us, when it is you personally who develops Checkstyle ... You are #3 contributor (which is great) – barfuin Feb 04 '16 at 21:16

2 Answers2

2

For PMD you can write rule like this:

<rule name="Prohibited classes"
      language="java"
      message="Avoid using these classes."
      class="net.sourceforge.pmd.lang.rule.XPathRule" >
    <description>
        Avoid using these classes, there are better alternatives.
    </description>
    <priority>3</priority>
    <properties>
        <property name="xpath">
            <value>
                <![CDATA[
//Name[pmd-java:typeIs('org.apache.commons.lang3.CharEncoding')] |
//Name[pmd-java:typeIs('org.apache.commons.lang.CharEncoding')] |
//Name[pmd-java:typeIs('org.apache.commons.codec.CharEncoding')]
]]>
            </value>
        </property>
    </properties>
</rule>

Or //Name[starts-with(@Image, 'com.sun.')] to prohibit package import.

valodzka
  • 5,535
  • 4
  • 39
  • 50
1

You can try to use these pmd extensions to blacklist classes and methods: https://github.com/LiveRamp/pmd_extensions

tcb
  • 2,745
  • 21
  • 20