我想製作自己的SonarQube規則,規則的目標是檢查變量和等號之間是否應該有空格。例如:ClassCastException:org.sonar.java.model.declaration.VariableTreeImpl
int num=3; // Noncompliant
int num = 3; // Compliant
要做到這一點,我試圖讓VariableTreeImpl
使用的方法equalToken()
。所以我應該改變類型VariableTree
到VariableTreeImpl
@Override
public void visitClass(ClassTree tree) {
if (tree.is(Tree.Kind.CLASS) || tree.is(Tree.Kind.ENUM)) {
for (Tree member : tree.members()) {
if (member.is(Tree.Kind.VARIABLE)) {
if (((VariableTree) member).initializer() != null && ((VariableTreeImpl)member).equalToken()!= null ){
SyntaxToken variableFistToken = ((VariableTree) member).simpleName().firstToken();
SyntaxToken initializerToken = ((VariableTree) member).initializer().firstToken();
if (noSpacingBetweenEqualSign(variableFistToken,initializerToken,((VariableTreeImpl) member).equalToken())) {
context.reportIssue(this, member, "Before and after equals sign should have white space");
}
}
}
}
}
super.visitClass(tree);
}
看來期間JUnit測試,以很好地工作,但是當我啓動蔡司鏡頭,掃描儀對我的測試項目中,我得到以下錯誤:
Caused by: java.lang.ClassCastException: org.sonar.java.model.declaration.VariableTreeImpl cannot be cast to org.sonar.java.model.declaration.VariableTreeImpl
at com.gisquest.custom.sonar.check.DeclareVariableCheck.visitClass(DeclareVariableCheck.java:39)
at org.sonar.java.model.declaration.ClassTreeImpl.accept(ClassTreeImpl.java:198)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:43)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:37)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.visitCompilationUnit(BaseTreeVisitor.java:55)
at org.sonar.java.model.JavaTree$CompilationUnitTreeImpl.accept(JavaTree.java:184)
at org.sonar.plugins.java.api.tree.BaseTreeVisitor.scan(BaseTreeVisitor.java:43)
at com.gisquest.custom.sonar.check.DeclareVariableCheck.scanFile(DeclareVariableCheck.java:29)
at org.sonar.java.model.VisitorsBridge.visitFile(VisitorsBridge.java:121)
at org.sonar.java.ast.JavaAstScanner.simpleScan(JavaAstScanner.java:84)
... 38 more
ERROR:
我有做了一些研究,我碰到這個問題,這看起來是我的問題: SonarQube java.lang.ClassCastException: ParametrizedTypeJavaType cannot be cast to ParametrizedTypeJavaType
所以我完全困惑。處理我的問題有什麼好方法?
我正在使用SonarQube版本6.2。
感謝Michael在我的pom.xml中我使用 4.3.0.7717 –
最新發布的SonarJava版本是'4.12.0.11033'。我建議您將您的項目和SonarQube實例更新到最新版本。請注意,我的評論仍然有效。訪問等於令牌的新方法將成爲'4.13'的一部分。 –