Custom Rule for Sonar Java.

128 views
Skip to first unread message

Abdelkader Ezzine

unread,
Jun 4, 2018, 8:46:03 AM6/4/18
to SonarQube
Good morning everybody,

I am trying to implement some custom rules, and I'm having trouble to implement a rule which require me to gather all the incoation of a certain method (doMethod); in certain classes for an example : obj.doMethod() , this case works perferctly, but in the the case of multiple method invocations, lets say : ClassA.getObj.doMethod(), I can't seem to find a way separate the expression's components ( ClassA, getObj).

Any help ?

I am using:
Sonar Plugin api 6.7
Sonar Java Plugin 5.1.0.13090


Andrei Epure

unread,
Jun 8, 2018, 5:15:03 AM6/8/18
to SonarQube
Hi Abdelkader,

Could you give some more information on what you want to achieve? Maybe the implementation you have so far (the relevant snippets)? And more code samples with what you want to find (on separate lines, to be easier to read)?

What I don't understand in your example: ClassA.getObj.doMethod() . Is getObj a static field of ClassA?

Regards,
Andrei

P.S.: Starting June 11th we'll have a new awesome forum. Details here

Andrei Epure | SonarSource

Software Developer

https://sonarsource.com


Are you using SonarLint in your IDE?


Andrei Epure

unread,
Jun 8, 2018, 9:00:37 AM6/8/18
to SonarQube
As general hints, you can play with MEMBER_SELECT and/or METHOD_INVOCATION for what you need.

public class YourRule extends IssuableSubscriptionVisitor {

 
@Override
 
public List<Tree.Kind> nodesToVisit() {
   
// Register to the kind of nodes you want to be called upon visit.
   
return ImmutableList.of(
       
Tree.Kind.MEMBER_SELECT,
       
Tree.Kind.METHOD_INVOCATION);
 
}

 
@Override
 
public void visitNode(Tree tree) {
   
if (tree.is(Tree.Kind.MEMBER_SELECT)) {
     
MemberSelectExpressionTree mset = (MemberSelectExpressionTree) tree;
     
System.out.println(mset);
   
} else if (tree.is(Tree.Kind.METHOD_INVOCATION)) {
     
MethodInvocationTree mit = (MethodInvocationTree) tree;
     
System.out.println(mit);
   
}
 
}
}

Cheers,
Andrei

P.S.: Starting June 11th we'll have a new awesome forum. Details here

Reply all
Reply to author
Forward
0 new messages