Search code examples
javaannotationscheckstylepmdstatic-code-analysis

PMD/Checkstyle - Force usage of Constant in Annotation-Value


I have a java annotation @Foo(value = "MyValueA"). As it can only use a couple of values, I decided to put them as constants into a class. So a user can use @Foo(value = MyValues.A) instead.

How can I make PMD or Checkstyle enforce the usage of this constants, instead of raw Strings?


Solution

  • In PMD, you can create your own ruleset to define a custom rule using an XPath expression to match for cases where this annotation's value is set to a literal string:

    //NormalAnnotation[@AnnotationName = 'Foo']//MemberValuePair[@Image = 'value']/MemberValue//Literal