Sonar Java如何获取变量类的注释
我正在编写一个自定义插件来检测声明变量类型为Sonar Java如何获取变量类的注释,java,spring,sonarqube,Java,Spring,Sonarqube,我正在编写一个自定义插件来检测声明变量类型为MyOtherClass的类,并给出警告,因为MyOtherClass是prototype类型 基本上,我需要从MyClass中获取字段,需要在field(MyOtherClass)类中获取注释,并且需要找到注释值是否包含prototype这是您的答案吗 @Component public MyClass{ private MyOtherClass myOtherClass; @Autowired public MyClass(MyOtherCla
MyOtherClass
的类,并给出警告,因为MyOtherClass是prototype类型
基本上,我需要从MyClass中获取字段,需要在field(MyOtherClass)类中获取注释,并且需要找到注释值是否包含prototype
这是您的答案吗
@Component
public MyClass{
private MyOtherClass myOtherClass;
@Autowired
public MyClass(MyOtherClass myOtherClass){
this.myOtherClass = myOtherClass;
}
}
@Component
@Scope("prototype")// OR
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyOtherClass{
}
找到了一种读取变量类注释的方法。这是否回答了您的问题?不。我正在使用声纳源编写自定义规则-。Sonar使用api读取方法、变量和类。
public class MyClass {
private MyOtherClass myOtherClass;
public MyClass(MyOtherClass myOtherClass){
this.myOtherClass = myOtherClass;
}
public static void main(String[] args) {
Field[] declaredFields = MyClass.class.getDeclaredFields();
for(Field field:declaredFields){
Scope scope = field.getType().getAnnotation(Scope.class);
if(scope!=null){
String value = scope.value();
System.out.println(value);
}
}
}
}
@Scope("prototype")
public class MyOtherClass {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Scope {
String value();
}
@Override
public void visitNode(Tree tree) {
org.sonar.plugins.java.api.tree.VariableTree variableTree = (VariableTree) tree;
if (variableTree.type().symbolType().symbol().metadata().isAnnotatedWith(SCOPE_ANNOTATION_FQN)) {
System.out.println("prototype annotation found " + variableTree.symbol().metadata().toString());
reportIssue(variableTree.simpleName(), "This spring bean is of type PROTOTYPE");
}
}