自定义SonarQube规则以标识实例变量

时间:2018-09-12 22:16:20

标签: java sonarqube

我正在创建一个自定义的SonarQube规则,以警告包含特定字符串的实例变量名称。看来Kind.VARIABLE检测到所有变量,包括局部变量。有没有一种方法只能检测和处理实例变量?

1 个答案:

答案 0 :(得分:2)

为什么不检查父项的Kind?对于实例变量,它应该是CLASS

在实例变量中将BLABLA字符串设为bann的工作规则将如下所示。

@Rule(key = "Banned Keyword Rule")
public class BannedKeywordRule extends IssuableSubscriptionVisitor {
    // Define the word to ban
    private static final String BANNED_KEYWORD = "BLABLA";

    @Override
    public List<Tree.Kind> nodesToVisit() {
        //  visit only the variables
        return ImmutableList.of(Tree.Kind.VARIABLE);
    }

    @Override
    public void visitNode(Tree tree) {
        VariableTree variableTree = (VariableTree) tree;
        // check if parent is CLASS aka variable is instance
        if(variableTree.parent().is(Tree.Kind.CLASS) && variableTree.simpleName().name().contains(BANNED_KEYWORD)) {
            reportIssue(variableTree, "String " + BANNED_KEYWORD + " can not be used as a instance variable.");
        }
    }
}