如何在运行时收集实现接口的所有类? [英] How to collect all classes implementing an interface at runtime?
问题描述
为了自动运行我的所有测试类,我查找专用目录中的所有类文件,将路径转换为包名并检查此类是否实现给定的接口:
For running all my test classes automatically, I look for all class files inside a dedicated directory, convert the path to a package name and check if this class implements the given interface:
try {
Class<? > myTestClass = Class.forName( constructedClassName );
if( myTestClass.isInstance( MyTestInterface.class ) ) {
testCollection.add( myTestClass );
}
}
catch( Error e ) {
// ignore, no valid test class
}
今天我遇到了一个丑陋的小虫(看到这个问题)使用这种技术。
Today I ran into an ugly bug (see this SO question) using this technique.
如何收集我的所有测试类而不必忽略我不感兴趣的类可能出现的错误?
How can I collect all my test classes without having to ignore Errors that can occur with classes I'm not interested in?
推荐答案
如何收集我的所有测试类而不必忽略我不感兴趣的类可能出现的错误?
How can I collect all my test classes without having to ignore Errors that can occur with classes I'm not interested in?
你在这里画了一个角落...
You've kind of painted yourself into a corner here ...
我要做的就是一个(或者更多)以下内容:
What I'd do is one (or more) of the following:
-
修复有问题的类,以便他们做加载
将这些类放在不同的位置目录,创建名称列表或使用模式匹配来区分您不希望添加到 testCollection
put the classes into different directories, create lists of names, or use pattern matching to discriminate between the classes that you do / don't want to add to testCollection
并记录错误当然!!也许将它们记录在不同的地方,但如果这样做,请在主日志中留下响亮消息,告诉某人在哪里查找详细信息。
And log the Errors of course!! Maybe log them somewhere different, but if you do that leave a loud message in the main log that tells someone where to look for details.
这篇关于如何在运行时收集实现接口的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!