PMD 查找注释并检查是否具有属性

PMD find annotation and check if has attribute

如何编写 PMD 规则来搜索 javax.validation.constraints.NotNull 注释并验证它是否具有消息属性?

差:

@NotNull
private int value;

@NotNull(message = "value cannot be null.")
private int value;

我主要关心的是这个注释基本上可以放在任何地方

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })

这是查找没有消息的 NotNull 注释的 xpath 查询: //Annotation[*/Name/@Image = 'NotNull' and not(.//MemberValuePair/@Image = 'message')]

我已经测试了除 ANNOTATION_TYPE 以外的所有情况,我不确定如何在 PMD 构建器应用程序中进行测试。

如果你想要全部 javax.validation.constraints 我想出了这个: //Annotation[*/Name/@Image = tokenize(replace(string-join(//ImportDeclaration/Name/@Image[starts-with(., "javax.validation.constraints.")], "|"), "javax.validation.constraints.", ""), '[|]') and not(.//MemberValuePair/@Image = 'message')]

所以:获取所有以 javax.validation.constraints. 开头的导入,使用 string-join 转换为字符串,使用 replace 删除 javax.validation.constraints. 并拆分回一组值tokenize.