I am trying to make my own SonarQube rule, the objective of the rule is to check that I am not using the contains method on a collection of a specific object. Example with Integer Object :
List<Integer> a = new ArrayList<>();
a.contains(1); // Noncompliant
To do that I am trying to get the ParametrizedTypeJavaType. Then I will be able to test if it is an Integer or not ...
@Override
public void visitNode(Tree tree) {
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) tree;
ExpressionTree expressionTree = ((MethodInvocationTree) tree).methodSelect();
if(expressionTree.is(Kind.MEMBER_SELECT)){
MemberSelectExpressionTree memberSelectExpressionTree = (MemberSelectExpressionTree) expressionTree;
Type type = memberSelectExpressionTree.expression().symbolType();
ParametrizedTypeJavaType parametrizedTypeJavaType = (ParametrizedTypeJavaType) type;
// SOME CODE Test if it is an integer or not ...
reportIssue(tree,"REPORT !");
}
}
@Override
public List<Kind> nodesToVisit() {
List<Kind> kinds = new ArrayList<>();
kinds.add(Kind.METHOD_INVOCATION);
return kinds;
}
}
It seems to work well during jUnit test but when i launched sonnar-scanner on my test project I get the following error :
Caused by: java.lang.ClassCastException: org.sonar.java.resolve.ParametrizedTypeJavaType cannot be cast to org.sonar.java.resolve.ParametrizedTypeJavaType
at org.sonar.samples.java.checks.CollectionCheck.visitNode(CollectionCheck.java:38)
I have done some research and I came across this question, that looks to be my problem :
Sonarqube error java.lang.ClassCastException: org.sonar.java.resolve.SemanticModel cannot be cast to org.sonar.java.resolve.SemanticModel
I came also across this rule which looks very similar to my rule and uses ParametrizedTypeJavaType.
https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/main/java/org/sonar/java/checks/CollectionInappropriateCallsCheck.java
So I am totally confused. What is the good approach to deal with my problem ?
SonarQube version : 6.3.1
Thanks for your help.