Getting parameters inside an Expression for declared variable

Hello,

Sonarqube v9.9.4

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.

In short, I am trying to get ClassC.class.

Regards,
Spectrolus

Hi,

Welcome to the community!

Can you share your code?

 
Thx,
Ann

Hello,

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.

Hi,

Thanks for sharing your code. I’m officially out of my depth at this point. :sweat_smile: So I’ve flagged this for more expert eyes.

 
Ann

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 (visitClass visitVariable) I can pull class and what variable I am currently looking at.

This can be closed.

2 Likes

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.

Cheers,
Angelo

1 Like