finding classes in a series of jar files that implement a specific interface
Hi, I'm trying to solve the following problem but I'm stumped as to how
I can do it 'properly' :(
I have a set of jar files containing classes and I would like to make
a list of names of the classes that implement an interface, say, X.
The code I'm using is given below. The problem is that I get
ClassDefNotFound and UnsatisfiedLinkError exceptions. I can see why
this would happen: a class, C, depends on another class B, which I
don't have in my jar file (or classpath) because I don't need C in the
first place.
However the code has to try and examine each and every class to
determine it's interface.
My question is: is it at all possible to try and load a class with
loading the classes it depends on and still be able to the information
regarding the interfaces implemented? I know that I could subclass
ClassLoader - but I did a naive implementation and for every class it
tried to load I got a ClassNotFoundException.
Any pointers towards a solution would be very appreciated.
--8<-------------------------------------------------------------
for (int i = 0; i < jars.length; i++) {
JarFile j;
try {
j = new JarFile(jars[i]);
Enumeration e = j.entries();
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.toString().indexOf(".class") != -1) {
String className = je.toString().replace('/',
'.').replaceAll(".class", "");
if (className.indexOf("$") != -1) continue;
Class klass = null;
try {
Class.forName(className);
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
if (klass == null) continue;
// check that its not abstract or an interface
int modifer = klass.getModifiers();
if (Modifier.isAbstract(modifer) ||
Modifier.isInterface(modifer)) continue;
// get the interfaces implemented and see if one matches the one
we're looking for
Class[] interfaces = klass.getInterfaces();
for (int k = 0; k < interfaces.length; k++) {
if (interfaces[k].getName().equals(interfaceName)) {
classlist.add(className);
break;
}
}
}
}
} catch (IOException e) {
}
}