[英]SonarQube (SonarLint /Sonar-JAVA) Redundant casts should not be used
[英]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.