I am trying to develop one custom rule, I want to access the parameters inside an Expression Method here for the declared variable.
private static final Logger LOGGER = LoggerFactory.getLogger(ClassC.class)
With the above example, I am currently able to access all fields except the parameters inside getLogger(). visitMethod does not look inside Expressions.
Thank you for your time. I can provide a snippet, I’m still new to sonar-java, feel free to ask any questions if I forgot to add anything.
public class ExampleClass extends BaseTreeVisitor implements JavaFileScanner {
@Override
public void visitMemberSelectExpression(MemberSelectExpressionTree tree) {
super.visitMemberSelectExpression(tree);
tree.expression() // this will return `LoggerFactory`
tree.identifier().name() // this will return `getLogger`
ExpressionsHelper.concatenate((ExpressionTree) tree); // this will return `LoggerFactory.getLogger`
}
}
I left some comments on each line on what I’ve been able to obtain so far.
I still don’t know how to access the parameters in expression, that being ClassC.class
private static final Logger LOGGER = LoggerFactory.getLogger(ClassC.class)
I’ve been using java-checks\src\main\java\org\sonar\java\checks\DisallowedClassCheck.java
in the sonar-java project as something to study as it goes through multiple different types of overrides.
I figured out the solution and a bit more about sonar-java. visitMemberSelectExpression does get the parameters of a declared expression, but at the next iteration it’s called.
So first iteration it’ll get LoggerFactory.getLogger and then it’ll get the parameters ClassC.class as the next iteration.
Using the other @Overrides (visitClassvisitVariable) I can pull class and what variable I am currently looking at.
Hello @Spectrolus, I’m glad that you managed to find a solution.
I would recommend you take a look at how existing rules are implemented so you can explore different approaches.
In your specific case, the best way to access the arguments of a method invocation is to extend from AbstractMethodDetection and override the onMethodInvocationFound, see this example. A more generic and flexible way is extending IssuableSubscriptionVisitor.
Please note that the Sonar Community is not meant to request help in writing custom rules or code, although we are always happy to provide help and support.