yegor256 yegor256 - 1 year ago 254
Java Question

How to disable a particular checkstyle rule for a particular line of code?

I have a checkstyle validation rule configured in my project, that prohibits to define class methods with more than 3 input parameters. The rule works fine for my classes, but sometimes I have to extend third-party classes, which do not obey this particular rule.

Is there a possibility to instruct "checkstyle" that a certain method should be silently ignored?

BTW, I ended up with my own wrapper of checkstyle: (see Strict Control of Java Code Quality)

Answer Source

Check out the use of the supressionCommentFilter at You'll need to add the module to your checkstyle.xml

<module name="SuppressionCommentFilter"/>

and it's configurable. Thus you can add comments to your code to turn off checkstyle (at various levels) and then back on again through the use of comments in your code. E.g.

public void someMethod(String arg1, String arg2, String arg3, String arg4) {

Or even better, use this more tweaked version:

<module name="SuppressionCommentFilter">
    <property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
    <property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
    <property name="checkFormat" value="$1"/>

which allows you to turn off specific checks for specific lines of code:

//CHECKSTYLE.OFF: IllegalCatch - Much more readable than catching 7 exceptions
catch (Exception e)
//CHECKSTYLE.ON: IllegalCatch

See also

<module name="SuppressionFilter">
    <property name="file" value="docs/suppressions.xml"/>

under the SuppressionFilter section on that same page, which allows you to turn off individual checks for pattern matched resources.

So, if you have in your checkstyle.xml:

<module name="ParameterNumber">
   <property name="id" value="maxParameterNumber"/>
   <property name="max" value="3"/>
   <property name="tokens" value="METHOD_DEF"/>

You can turn it off in your suppression xml file with:

<suppress id="maxParameterNumber" files=""/>

Another method, now available in Checkstyle 5.7 is to suppress violations via the @SuppressWarnigns java annotation. To do this, you will need to new modules (SuppressWarningsFilter and SuppressWarningsHolder) in your configuration file:

<module name="Checker">
   <module name="SuppressWarningsFilter" />
   <module name="TreeWalker">
       <module name="SuppressWarningsHolder" />

Then, within your code you can do the following:

  public void someLongMethod() throws Exception {

or, for multiple suppressions:

  @SuppressWarnings({"checkstyle:executablestatementcount", "checkstyle:methodlength"})
  public void someLongMethod() throws Exception {

The "checkstyle:" prefix is optional (but recommended) and the parameter name should be in all lowercase.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download