java - Find classes implementing an interface in Jar -
i want find whether classes inside jar has implemented particular interface or not. have implemented below code, iterates on classes inside jar file , finds on each class whether has implemented 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 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 simple way ? because if have jar 100 class files , 100th class has implemented interface, through above code need iterate 100 class files , find whether has implemented interface or not. there efficient way of doing ?
the reflections library can that:
reflections reflections = new reflections( classpathhelper.forpackage("your.root.package"), new subtypesscanner()); set<class<? extends yourinterface>> implementingtypes = reflections.getsubtypesof(yourinterface.class);
Comments
Post a Comment