11
I want to find whether the classes inside the jar has implemented a particular interface or not. I have implemented below code, but it iterates over all the classes inside jar file and finds on each class whether it has implemented this particular interface or not.
public static synchronized boolean findClassesInJar(final Class<?> baseInterface, final String jarName){
final List<String> classesTobeReturned = new ArrayList<String>();
if (!StringUtils.isBlank(jarName)) {
//jarName is relative location of jar wrt.
final String jarFullPath = File.separator + jarName;
final ClassLoader classLoader = this.getClassLoader();
JarInputStream jarFile = null;
URLClassLoader ucl = null;
final URL url = new URL("jar:file:" + jarFullPath + "!/");
ucl = new URLClassLoader(new URL[] { url }, classLoader);
jarFile = new JarInputStream(new FileInputStream(jarFullPath));
JarEntry jarEntry;
while (true) {
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null)
break;
if (jarEntry.getName().endsWith(".class")) {
String classname = jarEntry.getName().replaceAll("/", "\\.");
classname = classname.substring(0, classname.length() - 6);
if (!classname.contains("$")) {
try {
final Class<?> myLoadedClass = Class.forName(classname, true, ucl);
if (baseInterface.isAssignableFrom(myLoadedClass)) {
return true;
}
} catch (final ClassNotFoundException e) {
}
}
}
}
return false;
}
Is there any simple way to do this ? Because I