简体   繁体   中英

Custom SonarQube Rule to identify instance variables

I am creating a custom SonarQube rule to warn about instance variables names that contain a particular string. It appears that Kind.VARIABLE detects all variables, including local variables. Is there a way to detect and handle instance variables only?

Why not to check for the Kind of the parent ? For the instance variables it should be a CLASS .

Working Rule which bann's the BLABLA string in the instance variables will look something like this.

@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.");
        }
    }
}

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