[英]SonarQube: Create custom rules to get custom annotations in a class
我正在嘗試創建一個自定義SonarQube規則,該規則將檢測特定自定義Java Annotation的用法。 這是我找到的代碼,它打印了一個類中使用的所有注釋的列表。
public class SampleAnnotationCheck extends IssuableSubscriptionVisitor {
@Override
public List<Tree.Kind> nodesToVisit() {
return ImmutableList.of(Tree.Kind.METHOD);
}
@Override
public void visitNode(Tree tree) {
MethodTree methodTree = (MethodTree) tree;
for (AnnotationInstance ai : ((JavaSymbol.MethodJavaSymbol) methodTree.symbol()).metadata().annotations()) {
System.out.println(ai.symbol().name());
}
}
}
示例Java文件:
@GET
@Path(values)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
method1(...) {...}
@CustomAnnotation(values)
@POST
@Path(values)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
method2(...) {...}
@PATCH
@Path(values)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
method3(...) {...}
預期產出:
GET
Path
Consumes
Produces
CustomAnnotation
POST
Path
Consumes
Produces
PATCH
Path
Consumes
Produces
實際產量:
GET
Path
Consumes
Produces
!unknownSymbol!
POST
Path
Consumes
Produces
!unknownSymbol!
Path
Consumes
Produces
我得到了!unknownSymbol! 而不是自定義批注的實際名稱。 其中一個自定義注釋是io.swagger.jaxrs.PATCH。
另一個注釋在單獨的包中定義,並由樣本類導入。
我們是否必須在某處注冊這些自定義注釋以供API檢測?
請建議應進行哪些更改,以便我們可以檢測並打印實際的自定義注釋的名稱。
提前致謝!
我假設您正在遵循本指南並在測試中運行檢查https://docs.sonarqube.org/display/PLUG/Writing+Custom+Java+Rules+101 。 要為測試提供依賴關系,您也可以
將jar放在target/test-jars
目錄中(請參閱https://github.com/SonarSource/sonar-custom-rules-examples/blob/master/java-custom-rules/pom,了解如何使用maven依賴插件。 xml#L147 )
在您的測試中使用JavaCheckVerifier.verify(filename, check, classpath)
提供自定義類JavaCheckVerifier.verify(filename, check, classpath)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.