Read annotations on a variable's type 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.

I need to get fields from MyClass and need to get Annotations on the field(MyOtherClass) class and need to find if the annotation value contains prototype.

I am using VariableTree to read the variable but not finding a way to get into variable class metadata.

I can do it on class by using ClassTree.

@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.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.