简体   繁体   中英

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

I am writing a custom plugin to detect classes which declare variable of type MyOtherClass and give a warning because MyOtherClass is of type prototype.

Basically I need to get field from MyClass and need to get Annotation on the field(MyOtherClass) class and need to find if the annotation value contains 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");
    }
}

Found a way to read annotations on a variable class.

Is this your answer?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM