如何编写涉及间接继承的Checkstyle自定义检查? [英] How to write a Checkstyle custom check involving indirect inheritance?

查看:92
本文介绍了如何编写涉及间接继承的Checkstyle自定义检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要编写一个checkstyle自定义检查,以验证从某个类A直接或间接继承的类的特定条件。是否可以使用checkstyle API识别间接继承?
例如,假设我们有:

We need to write a checkstyle custom check that verifies a specific condition for classes that inherit—directly or indirectly—from a certain class A. Is it possible to identify the indirect inheritance using the checkstyle API? For example, suppose we have:


  • C类---扩展---> B类

  • B类---扩展---> A类

在这种情况下,很容易检查C是B的子类,它通过查找 extends令牌( TokenTypes.EXTENDS_CLAUSE )并在extends子句AST中查找B。但是我们怎么知道C也是A的子类呢?

In this case, it’s easy to check that C is a subclass of B by looking for the "extends" token (TokenTypes.EXTENDS_CLAUSE) and looking for B in the extends clause AST. But how can we know that C is also a subclass of A?

Java反射加instanceof是唯一的出路吗? (在我们的情况下,不可取,因为我们必须对数千个文件进行检查。)

Is Java reflection plus instanceof the only way out? (Not desirable in our case as we have to run the check over thousands of files.)

PMD或其他静态分析工具是否可以让我编写具有(间接继承)条件的自定义检查?

Would PMD or another static analysis tool allow me to write a custom check with that (indirect inheritance) condition?

推荐答案

这是可以做到的,但并不容易,因为checkstyle没有Java编译器。因此,它只能查看源文本并分析其语法树,而不能理解它。

It can be done, but not easily, because checkstyle has no Java compiler. So it can only look at the source text and analyze its syntax tree, but it cannot "understand" it.

因此,必须 load

为此,您很可能需要定义自己的类加载器,以便可以从中加载类,例如,您的日食工作区(或从其他来源获取)。

For this, you will most likely need to define your own class loader, so that you can load the class from, let's say, your eclipse workspace (or from whereever else your sources are).

现在,您只需调用 instanceof A 即可, !

Now you can simply call instanceof A and voilà!

我不会担心性能。您可以将LRU的类文件缓存添加到自定义的类加载器中,这样可以解决该问题。另外,如果检查在您的IDE中运行,则只需要加载很少的类(直接继承树中的类),并且如果它在整个源代码上运行,它将在晚上运行,不是吗?

I wouldn't worry about performance. You could add an LRU cache of class files to your custom class loader, which would resolve that. Also, if the check runs in your IDE, it only needs to load very few classes (those in the direct inheritance tree), and if it runs on the entire source, it will run at night, no?

由于这个问题已经很老了,请告诉我您是否需要代码示例。

Since this question is already quite old, let me know if you need a code example.

这篇关于如何编写涉及间接继承的Checkstyle自定义检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆