Vladimir Topolev
Vladimir Topolev

Reputation: 394

SonarQube. Create custom rule for Java

anyone can help me with this case.

I have the next test file:

AWSCredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
AmazonWebServiceClient client = new AmazonS3Client(provider); // Noncompliant 

Are there way to extract the particular implementation of interface from the variable provider when I explore the arguments of constructor AmazonS3Client? Now I can extract AWSCredentialsProvider for this variable only.

Upvotes: 0

Views: 113

Answers (1)

Wohops
Wohops

Reputation: 3121

As it's not that explicit, I'm guessing that you are trying to retrieve implementation type used to initialize th providervariable, which would be EnvironmentVariableCredientialsProvider.

There is currently no easy and straightforward way to achieve this. The best way would be to proceed as follow:

  • From the provider IdentifierTree, use the semantic API to get to the corresponding symbol.
  • From the provider symbol, jump to the declaration tree (which will be null if the identifier is declared in another file).
  • From the declaration, and if the tree is a VariableTree, look for the initializer expression.
  • From the ExpressionTree, get the type of the symbol Type, which will give you the implementation type.

That's a first step which should help you to get further. Of course you will next probably need to handle cases where the variable is declared without initializer, and then assigned somewhere else. To retrieve these expressions, look at the symbol usages, instead of declaration, and walk the trees.

Upvotes: 1

Related Questions