The following code loads all classes from a JAR file. He does not need to know anything about classes. Class names are retrieved from JarEntry.
JarFile jarFile = new JarFile(pathToJar); Enumeration<JarEntry> e = jarFile.entries(); URL[] urls = { new URL("jar:file:" + pathToJar+"!/") }; URLClassLoader cl = URLClassLoader.newInstance(urls); while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if(je.isDirectory() || !je.getName().endsWith(".class")){ continue; } // -6 because of .class String className = je.getName().substring(0,je.getName().length()-6); className = className.replace('/', '.'); Class c = cl.loadClass(className); }
edit:
As suggested in the comments above, the javassist will also be an opportunity. Initialize ClassPool somewhere before the while loop, generating the code above, and instead of loading the class with the class loader, you can create a CtClass object:
ClassPool cp = ClassPool.getDefault(); ... CtClass ctClass = cp.get(className);
From ctClass you can get all methods, fields, nested classes, .... Take a look at javassist api: https://jboss-javassist.imtqy.com/javassist/html/index.html
Apfelsaft Jun 13 2018-12-12T00: 00Z
source share