SonarQube java.lang.ClassCastException: Parametriz

2019-08-01 03:14发布

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.

1条回答
别忘想泡老子
2楼-- · 2019-08-01 03:21

ParametrizedTypeJavaType is not part of the java api for custom rule. And as of today semantic API does not allow you to access to generics information : This is planned but not scheduled : https://jira.sonarsource.com/browse/SONARJAVA-1871

You are better off relying on the existing rule for what you want to achieve : https://sonarqube.com/coding_rules#rule_key=squid%3AS2175

If this rule does not work correctly for you can you explain why ?

查看更多
登录 后发表回答