9

I have the following code which uses lombok @Value for generating a immutable class:

@Value
public class InputDTO {
    String field;
}

but unfortunately it doesn't agree with checkstyle visibility modifier checks which complains with this error:

Variable 'field' must be private and have accessor methods. (18:10) [VisibilityModifier]

I have found a workaround suppressing the check like this:

@SuppressWarnings("checkstyle:VisibilityModifier")

But is there a way to make checkstyle validate lombok's generated code rather than the plain original code?

Fede Garcia
  • 677
  • 11
  • 18

2 Answers2

7

There is a way to disable this violation in checkstyle.xml config once rather than using @SuppressWarnings in every file and pollute your production code.

With the SuppressionXpathSingleFilter you can do:

<module name="TreeWalker">
    <module name="SuppressionXpathSingleFilter">
        <property name="checks" value="VisibilityModifier"/>
        <property name="query" value="//*[MODIFIERS//*[@text = 'Value']]/descendant-or-self::node()"/>
    </module>
</module>
pavelicii
  • 1,590
  • 11
  • 21
  • is it possible to apply this configuration only to classes with a given suffix (e.g. *Dto, *Request, *Response...)? – Fede Garcia Nov 17 '20 at 07:27
  • ah, yes, I see you can filter by file name like this, right? `` – Fede Garcia Nov 17 '20 at 07:43
  • Yes, just checked it and it also works with files like you suggested. But I'm not sure why you need to use this approach. With `query` property I suggested, `VisibilityModifier` check will still be applied to all classes without lombok's `@Value` annotation. – pavelicii Nov 17 '20 at 11:07
  • This will pass if we have an inner class without private and `@Value` but the parent class has `@Value`. That is not the intended outcome – Tino M Thomas May 26 '21 at 16:11
1

There is no way to do it. Lombok's magic is applied on compile phase, but checkstyle only analyzes code in file as text, not bytecode.

strkk
  • 589
  • 3
  • 7
  • late comment from me but this seems like a design flaw if we can't get immutable classes working OOTB. – user2103008 Jun 14 '23 at 07:09
  • @user2103008 such approach has its advantages as well, e.g. you dont need to spend time on compilation, since it works with plain text. – strkk Jul 10 '23 at 19:08