Sonarqube error java.lang.ClassCastException: org.

2019-06-25 05:09发布

问题:

Hi I wrote own plugin for sonar 5.1.2 based on some checks from java-web-plugin 3.5 (dependency in pom for java-checks 3.5) and when I try to run analysis on project i get error:

Caused by: java.lang.ClassCastException: org.sonar.java.resolve.SemanticModel cannot be cast to org.sonar.java.resolve.SemanticModel
    at org.sonar.java.checks.SubscriptionBaseVisitor.scanFile(SubscriptionBaseVisitor.java:32)
    at org.sonar.java.model.VisitorsBridge.visitFile(VisitorsBridge.java:123)
    at org.sonar.java.ast.JavaAstScanner.simpleScan(JavaAstScanner.java:94)
    ... 38 more

for example i copied to my plugin code from BadMethodName_S00100_Check.java and changed only class name, description and issue info. Why am I getting error? Other checks which don't use semanticModel works just fine.

回答1:

This is because the class SemanticModel is not designed to be used in custom rules and is not part of the API. As such, you are encountering an error at runtime as this class is not made available whereas we can't "forbid" you to use it during compilation. Please see http://sonarqube-archive.15.x6.nabble.com/How-to-use-JavaFileScannerContext-getSemanticModel-td5029996.html for more details. This limitation is done by SonarQube plugin packaging. I guess the error message should be mroe explicit (yes, this is an understatement).

If you want to access semantic information please use the semantic API from the tree nodes to access symbols and types.