如何编写涉及间接继承的Checkstyle自定义检查?
我们需要编写一个 checkstyle 自定义检查来验证直接或间接继承自某个类 A 的类的特定条件。是否可以使用 checkstyle API 来识别间接继承? 例如,假设我们有:
- Class C ---extends---> B类
- B类---延伸--->类 A
在这种情况下,通过查找“extends”标记 (TokenTypes.EXTENDS_CLAUSE
) 并在 extends 子句 AST 中查找 B,可以轻松检查 C 是否是 B 的子类。但是我们怎么知道C也是A的子类呢?
Java反射加上instanceof是唯一的出路吗? (在我们的例子中并不理想,因为我们必须对数千个文件进行检查。)
PMD 或另一个静态分析工具允许我使用该(间接继承)条件编写自定义检查?
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:
- Class C ---extends---> class B
- Class B ---extends---> class 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?
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.)
Would PMD or another static analysis tool allow me to write a custom check with that (indirect inheritance) condition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是可以做到的,但并不容易,因为 checkstyle 没有 Java 编译器。所以它只能看源文本并分析其语法树,但无法“理解”它。
因此,您必须从 checkstyle 检查中加载该类。
为此,您很可能需要定义自己的类加载器,以便您可以从您的 Eclipse 工作区(或者您的源所在的任何其他位置)加载该类。
现在您只需调用
instanceof A
即可!我不会担心性能。您可以将类文件的 LRU 缓存添加到自定义类加载器中,这将解决该问题。另外,如果检查在您的 IDE 中运行,它只需要加载很少的类(直接继承树中的类),如果它在整个源上运行,它将在晚上运行,不是吗?
由于这个问题已经很老了,如果您需要代码示例,请告诉我。
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.
So, you must load the class from within your checkstyle check.
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).
Now you can simply call
instanceof A
and voilà!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.
我们已经用 Java 反射解决了这个问题:
它限制了自定义检查的适用性,因为它只有在 ClassA 和 ClassC 位于类路径中时才有效。
We have solved the problem with Java reflection:
It limits the applicability of the custom check though, because it only works if ClassA and ClassC are in the classpath.