Search code examples
javaclassdynamicloadingclassloader

Dynamic class loading from multiple JARs


Consider the following simple method that (attempts to) load all classes of a specific name, residing in a JAR file located in a specified path, i.e.

public static List<Class<?>> getAllClasses(String name, String path)
{
    File file = new File(path);

    try
    {
        URL url = file.toURI().toURL();

        URLClassLoader loader = URLClassLoader.newInstance(new URL[] {url});

        JarFile jar = new JarFile(file);

        Enumeration<JarEntry> entries = jar.entries();

        Class<?> type;

        String elementName;

        List<Class<?>> classList = new ArrayList<Class<?>>();

        while (entries.hasMoreElements())
        {
            elementName = entries.nextElement().getName();

            if (elementName.equals(name))
            {
                try
                {
                    type = loader.loadClass(elementName);
                    classList.add(type);
                }
                catch (Exception e)
                {
                }
            }
        }

        return classList;
    }
    catch (Exception e)
    {
    }

    return null;
}

If there are more than 1 JARs in the path, each of which has at least one class with an identical canonical name with an already loaded class, e.g. org.whatever.MyClass, is there any way, without customized class loaders, to load all org.whatever.MyClass classes?


Solution

  • Standard class loaders load classes in a single namespace. If you are looking for instances of a same class from different version implementations, then you must use custom class loaders. Your code snippet is an example for custom loading.

    You can refer to a detailed article published here.