Michael
Michael

Reputation: 44200

How can I enforce that enum constants must be uppercase in Checkstyle?

Suppose I have the following enum:

enum Colour
{
    RED   (1),
    GREEN (2),
    Blue  (3); // Invalid

    final int colourCode;

    Colour(final int code)
    {
        this.colourCode = code;
    }
}

I want Checkstyle to enforce that all of the enum constants must only contain uppercase characters, digits and underscores.

In this case Blue should throw an error, while everything else (including the member colourCode) is okay.

I've had a look at MemberName, ConstantName and StaticVariableName from the naming section of the documentation but none seem to apply, nor are you able to target them specifically at enums.

Upvotes: 1

Views: 839

Answers (1)

barfuin
barfuin

Reputation: 17494

Core Checkstyle cannot do that out-of-the-box, surprisingly. You'll have to use the Sevntu Checkstyle addon, which features the EnumValueNameCheck. I think the default behavior is just what you need, so you'd configure it thusly:

<module name="EnumValueName"/>

Be sure to add Sevntu Checkstyle to your Checkstyle classpath before running it. Their website has descriptions on how to do that in various scenarios.

Upvotes: 3

Related Questions