Get all methods declared inside a class

Hi,

Sonarqube v7.7

I am trying to develop one custom rule, for that i want to get all the method names declared inside a class and need to validate those names.

eg:

class A{
method A(){}
method B(){}
}

I have get all method names at a time instead of iterating each time.

Is there any way to get all method names?

Regards,
Anurag

Hello,

What have you already tried? Please share the code of your custom rule, and from there, we will try to help you. Note that this case should be pretty trivial once registered to METHOD trees… There is even multiple rules of the official examples doing similar things on top of methods. Please have a look here:

Now, if you just need just to validate names according to regex, there is even of the template rule already available in SonarJava: See squid:S100

Regards,
Michael

Hi,

I haven’t tried anything to get all method names.

I want to check whether default methods are implemented or not. For example,

If anyone using the api proxy they have to implement some methods like preFilter,errorFilter. As per my knowledge using visitMethod(), we can iterate over each method.

But when i write any validations it will raise issue on each method if it is not validated. Instead of iterating each method i want to get all methods/method names declared inside class. So, I can validate all at a time and i can flag the issue.

Hello,

You can extend org.sonar.plugins.BaseTreeVisitor and overide method visitMethod

class    BaseTreeVisitorImplementation extends BaseTreeVisitor  {
        @Override
         public void visitMethod(MethodTree tree) {
         super.visitMethod(tree);
        //colect all methods here
        }
       
        public void getMethods() {
        //return colected methods
        }
}

then just extend IssuableSubscriptionVisitor like Michael suggested. Overide folowing nodesToVisit method like this.

    @Override
    public List<Tree.Kind> nodesToVisit() {
    return Collections.singletonList(Tree.Kind.CLASS);
     }

    @Override
    public void visitNode(Tree tree) { 
    TreeVisitor methodCollector = new BaseTreeVisitorImplementation();
    tree.accept(methodCollector);
    methodCollector.getMethods();

    }
1 Like