Platinum Partner
java,devops,classloader

Java Classloader - Handling Multiple Versions of The Same Class

This article deals with different approaches to load multiple versions of the same class.

The problem

Many times during the development you will need to work with different libraries versions which not always backward compatible or from some reason you need to support multiple versions of the same library. 

Using standard Java classloaders will not solve this issue since they all use "loadClass" method to load a specific class only once. After that "loadClass" will return the reference of the existing Class instance.


The solution:

Using another classloader to load the library (or multiple classloaders).

There are several approaches available to achieve that:



  1. Use a URLClassLoader:

    This class loader will allow you to load your jars via URLs, or specify a directory for your classes location. 

    Here is an example:


URLClassLoader clsLoader = URLClassLoader.newInstance(new URL[] {new URL("file:/C://Test/test.jar")});
Class cls = clsLoader.loadClass("test.Main");
Method method = cls.getMethod("main", String[].class);
String[]params = new String[2];
method.invoke(null, (Object) params);



   2.   Write your own custom class loader.

         Since Java class loaders (including URLClassLoader) first ask to load classes from their
         parent class loader, you can encounter a situation where you will need your custom
         classloader to load the classes from your specified location first.

         In this case here is a sample of a custom class loader which do exactly that:



import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

public class CustomClassLoader extends ClassLoader 
{
    private ChildClassLoader childClassLoader;

    public CustomClassLoader(List<URL> classpath)
    {
        super(Thread.currentThread().getContextClassLoader());
        URL[] urls = classpath.toArray(new URL[classpath.size()]);
        childClassLoader = new ChildClassLoader( urls, new DetectClass(this.getParent()) );
    }

    @Override
    protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
    {
        try
        {
            return childClassLoader.findClass(name);
        }
        catch( ClassNotFoundException e )
        {
            return super.loadClass(name, resolve);
        }
    }

    private static class ChildClassLoader extends URLClassLoader
    {
        private DetectClass realParent;

        public ChildClassLoader( URL[] urls, DetectClass realParent )
        {
            super(urls, null);
            this.realParent = realParent;
        }

        @Override
        public Class<?> findClass(String name) throws ClassNotFoundException
        {
            try
            {
            Class<?> loaded = super.findLoadedClass(name);
                if( loaded != null )
                    return loaded;
                return super.findClass(name);
            }
            catch( ClassNotFoundException e )
            {
                return realParent.loadClass(name);
            }
        }
    }

    private static class DetectClass extends ClassLoader
    {
        public DetectClass(ClassLoader parent)
        {
            super(parent);
        }

        @Override
        public Class<?> findClass(String name) throws ClassNotFoundException
        {
            return super.findClass(name);
        }
    }
}
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}