Get the list of Method invocations on a single variable

Hello everybody,

I want to know if there is a straight forward way to get a list of MethodInvocations on a single variable ?


There is a no easy way to do that in the SonarJava API. You’ll need to do it mainly manually. Multiple approaches are however possible depending of your use case… Once you located the variable you want to target, and it’s associated symbol (subscription to VARIABLE? is it a field? a local variable? a method parameter?), then you can jump to all it’s usages. From any of the usage, you should be able to explore the tree (using - maybe iteratively - parent() method). And then locate when it’s the left hand side of a method invocations.

If you need more, it could help if you share the following:

  • What did you try already?
  • Can you share the code of your rule? (or equivalent if it can not be shared publicly)
  • Can you share the test code you are targeting with your rule? (again, anonymized if needed)


1 Like

The purpose is to add a Rule, so that I can check that certain treatment (mandatoryMethod()) has been done on an hibernate Entity, before getting (getSomeField()) a filed from that entity.

The first solution that came to my mind, is, whenever I find for example a.mandatoryMethod(), I add the object “a” to an ArrayTable.
And Then when browsing for the save() method invocation, I check if the object is in the table.
But, this solution is far from being the good one.

Here is a test code for this example:

class MyClass 
    void methodDefaulSequence() throws ServiceException {
	    classX x = new classX();
	    classX x2 = new classX();
	    x.getB();// Here we called mandatoryMethod() on object x, so it's OK.
        x2.getB(); //Here we raise a warning, cause we did not call mandatoryMethod() before this line.


I didn’t find a solution for this problem yet. Any help would be much appreciated.


To do this properly is a very hard problem : you will need to take care of different flow and track eventual reassignement. To be really short : this is a kind of analysis we are only starting to develop and mainly for bug detection and security rule and it is hard.

To do this (very) naively however, you can check all the usages of the variables you are interested in and check the mandatoryMethod has been called on a line “before” the call to a getter.
This would raise quite a lot of false positive though so beware.