簡體   English   中英

Sonar-Java如何獲取變量的注釋 class

[英]Sonar-Java how to get annotations of a variable class

@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{
}

我正在編寫一個自定義插件來檢測聲明類型為MyOtherClass的變量的類,並發出警告,因為 MyOtherClass 是原型類型。

基本上我需要從 MyClass 獲取字段並需要在字段 (MyOtherClass) class 上獲取注釋並且需要查找注釋值是否包含prototype

 @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");
    }
}

找到了一種讀取變量 class 注釋的方法。

這是你的答案嗎?

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM