I assume that you want to load a set of classes located in a JAR file or any other URL, and then return a list containing these class objects.
My recommendations:
- Use the
java.util.jar.JarFile class to read all the records in your bank. - Iterate over the elements, and if the given entry belongs to the class (its name ends with ".class"), you load the class and add it to the list of loaded classes.
Somewhat:
JarFile jar = new JarFile(jarFile); for(JarEntry entry: Collections.list(jar.entries())){ if(entry.getName().endsWith(".class")){ String className = entry.getName().replace("/", ".").replace(".class",""); foundClasses.add(loader.loadClass(className)); } }
For download purposes, you can use java.net.URLClassLoader containing your jar file.
Somewhat
File jarFile = new File("./jedis.jar"); URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()});
In the list of foundClasses you will get all the loaded classes.
On the other hand, if you know exactly the classes you want to load, then URLClassLoader is enough to fix the problem.
File jarFile = new File("./jedis.jar"); URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}); foundClasses.add(loader.loadClass("jedi.academy.ObiWan")); foundClasses.add(loader.loadClass("jedi.academy.Luke")); foundClasses.add(loader.loadClass("jedi.academy.Anakin"));
If you want this secondary class loader to be independent of the system class loader, be sure to set the parent class loader to null when creating the URLClassLoader instance:
URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}, null);
source share