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

Praveena DG
  • 143
  • 1
  • 8
  • 1
    Does this answer your question? [Is it possible to read the value of a annotation in java?](https://stackoverflow.com/questions/4296910/is-it-possible-to-read-the-value-of-a-annotation-in-java) – mentallurg Aug 04 '20 at 00:23

2 Answers2

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

Praveena DG
  • 143
  • 1
  • 8
-1

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();
}
  • No. I am writing custom rule using sonar source - https://github.com/SonarSource/sonar-custom-rules-examples. Sonar uses their api to read method, variable and classes. – Praveena DG Aug 04 '20 at 16:52