How to collect all classes implementing an interfa

2019-05-26 00:07发布

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.

Question:

How can I collect all my test classes without having to ignore Errors that can occur with classes I'm not interested in?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-26 00:42

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:

  • fix the offending classes so that they do load

  • 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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-05-26 00:48

What good is a class that does not load? Why not just fix them first? Wouldn't you have to fix them at some point?

查看更多
登录 后发表回答