I had a similar need where I wanted to make sure that any classes created that implemented a certain interface were always truly serializable. I created a JavaClassFinder which walks through all directories in the classpath, and finds all classes assignable to the interface I cared about. Here is a code snippet:
public <T> List<Class<? extends T>> findAllMatchingTypes(Class<T> toFind) {
foundClasses = new ArrayList<Class<?>>();
List<Class<? extends T>> returnedClasses = new ArrayList<Class<? extends T>>();
this.toFind = toFind;
walkClassPath();
for (Class<?> clazz : foundClasses) {
returnedClasses.add((Class<? extends T>) clazz);
}
return returnedClasses;
}
I'm happy to share the code with you if it helps. The only draw back is that this will only handle .class files -- I didn't add the feature to unzip .jars and read class files from there. (But it wouldn't be a huge project to add that.)
UPDATE: I checked my source code for the above, and found it depends on a lot of helper classes in our standard utility library. To make it easier, I zipped up all the code needed, which you can download from JavaClassFinder.zip. This will set up directly in Eclipse, and you can take whatever portions of the code you need.
You will find a JUnit3 test in the project, called JavaClassFinderTest.java, which shows you the features and usage of the JavaClassFinder class. The only external dependency needed to run the Junit test is Junit.
Basic usage of this utility:
JavaClassFinder classFinder = new JavaClassFinder();
List<Class<? extends MyTagInterface>> classes = classFinder.findAllMatchingTypes(MyTagInterface.class);
This will give you a List which contains any classes in the classpath which are assignable from the "MyTagInterface.class" (for example). Hope this helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…