我正在编写一个自定义规则,用于检查正在分析的类是否正在扩展类型。 例如:
班巴{ }
班级运输{ }
class PublicTransport extends Transport { }
类Bus应该扩展类Transport或子类的Transport。
public class EnsureSuperClassRule extends IssuableSubscriptionVisitor {
final String SUPER_CLASS = "common.service.SuperService";
@Override
public List<Tree.Kind> nodesToVisit() {
return ImmutableList.of(Tree.Kind.CLASS);
}
@Override
public void visitNode(Tree tree) {
ClassTree classTree = (ClassTree) tree;
String className = classTree.simpleName().name();
if (className.endsWith("Service")) {
if(classTree.superClass() == null) {
return false;
}
if (!SUPER_CLASS.equals(localClassTree.superClass().symbolType().fullyQualifiedName())) {
reportIssue(tree, String.format("The class should extend SuperService or a class of type SuperService"));
}
}
}
}
}
我的问题是如何获得与超类的超类相关的信息?
答案 0 :(得分:0)
您只需致电
即可Class superClassOfSuperClass = this.class().getSuperClass();
superClassOfSuperClass.method().invoke(this);
我不确定上面的例子,因为遗传有一些错误或误解
答案 1 :(得分:0)
您可以收集所有超级类,直到达到java.lang.Object
为止:
@Override
public void visitNode(Tree pTree) {
final ClassTree classTree = (ClassTree) pTree;
final Set<String> superclasses = new HashSet<>();
Type currentSuperclass = classTree.symbol().superClass();
while (currentSuperclass != null) {
superclasses.add(currentSuperclass.fullyQualifiedName());
currentSuperclass = currentSuperclass.symbol().superClass();
}
// ... do something with superClasses
super.visitNode(pTree);
}
@Override
public List<Kind> nodesToVisit() {
return ImmutableList.of(Tree.Kind.CLASS);
}
(已通过sonar-java-plugin 6.3.0和sonar-plugin-api 8.2.0测试)