I want to find whether the classes inside the jar were implemented by a specific interface or not. I have executed the code below, but it iterates over all classes inside the jar file and finds in each class whether it 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 an easy way to do this? Because If has a jar with 100 class files, and the 100th class implemented this interface, through the above code I need to iterate over all 100 class files and find out whether it implemented the interface or not. Is there an effective way to do this?
Mojoy source share