简体   繁体   中英

Checking for variable value using Checkstyle/PMD/Findbugs

I have a multi-modules Maven project currently running Checkstyle, PMD and Findbugs. In certain classes I have methods with annotations. These annotations have a parameter with a value that needs to follow a certain regex. Is there an easy way to look for this parameter value and verify if it follows the pattern using any of the previously mentioned tools. I have tried writing a custom check for Checkstyle. However, since Checkstyle only sees line by line, it cannot verify parameters that are set using final strings. I have looked around but couldn't find anything. Thank you very much.

Yes there is. This looks like a prime case for PMD's XPath rules .

You can write an XPath expression over the AST to match annotations that don't comply to your definition. Also, the designer is very useful to help you develop and test your rule.

So you could probably write something such as:

//Annotation[pmd-java:typeIs('java.lang.SuppressWarnings') and .//MemberValue//Literal[not(matches(@Image, '[0-9]+'))]]

Will match all @SuppressWarnings annotations, that have a value not matching [0-9]+ . You can further refine this to look for values of a specific key if needed.

Once you are ok with your XPath, you simply write it into your ruleset and can start running it on your codebase.

Notice the XPath given in the example is an XPath 2.0, as it uses the matches function not available in older versions. PMD supports XPath 1.0, 1.0 compat mode and 2.0, being 1.0 the default, but overridable in the rule definition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM