About Java custom rules


1.The number of called functions(Metrics name:CALLING)must be smaller or equal than 5.
2.The number of function calls(Metrics name:CALLS)must be smaller or equal than 7.

At present, I want to make the above two rules, but I can’t find useful attributes in the method tree.
Can you guys kindly help me how to make these two rules?Just give directions, such as what methods in what classes are used.

Hello @KevinJin,

The rules you are describing seem feasible with the tools available.

I suggest you take a look at the examples of custom rules, paying particular attention to the ones that explore methods, such as AvoidMethodDeclarationRule.
For other examples of the type of nodes you can visit, look at the BaseTreeVisitor and its API.

Hope this helps,


Hi @Dorian_Burihabwa ,

Thank you for your reply.

At present, I am using visitMethod(MethodTree tree) to try to get the content in the method body, but I have no way.
Do you have any common methods to get the content of method body?
hope you could reply to me as soon as possible.

Thank you again,


I used methodTree.block().body().get(0) to get the StatementTree object, and then found the content I wanted in the blue content. These contents can be seen in the debug state, but these attributes are not available in the actual development.

How could I get the data I want? Could you kindly give me some suggestions?



HI @KevinJin
There is probably a better way for you to design your check without checking all statements manually:

  • Make your check stop on method declarations
  • In method declarations, look for method invocations and count them

To do the second part of this check, you can implement a BaseTreeVisitor that stops on method invocations and increment a counter.

class MyCheck extends BaseTreeVisitor {

  void visitMethod(MethodTree tree) {
    InvocationVisitor iv = new InvocationVisitor();
    // Recover the counter from iv

  static class InvocationVisitor extends BaseTreeVisitor {
    void visitMethodInvocation(MethodInvocationTree tree) {
    // Increment my counter here

This should help a lot.


HI @Dorian_Burihabwa
Sorry, I don’t understand what you mean and how to get what I want.

Please,how to use visitMethodInvocation() to obtain the content in method declaration {} and then transfer the content to visitMethod()?

I’ve seen many visitMethodInvocation() in sonar-Java, but I haven’t been inspired by them. Since my appeal is relatively simple, can you kindly tell me how to write these two methods?

Please,thank you a lot.


Hi @Dorian_Burihabwa
I still have a lot of confusion about this question. Please tell me the meaning of counting method statement. I really don’t understand it.
I’m sorry to bother you again.