PNS
PNS

Reputation: 19895

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?

Upvotes: 1

Views: 2642

Answers (2)

Ravinder Reddy
Ravinder Reddy

Reputation: 23992

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.

Upvotes: 1

nsfyn55
nsfyn55

Reputation: 15363

No classes only get loaded once and the key for the class is Classloader+Fully Qualified Class Name. It will check the cache and the classloader chain and if it finds the class it won't try to load it again. Which one gets picked is implementation specific.

Upvotes: 1

Related Questions