Tip : Add resources dynamically to a ClassLoader

Theoretically, it's not possible to ad resources to a ClassLoader in Java after creation. I say theoretically, because, we can do that using Reflection.

In fact, the URLClassLoader class has a addUrl(URL url) method to add a new URL, so we can invoke that method to add an URL where the ClassLoader can search to load a class. But this method is protected. So here is an example taking advantage of Reflection to add URL to the system ClassLoader :

public static void addURLToSystemClassLoader(URL url) throws IntrospectionException { 
  URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); 
  Class<urlclassloader> classLoaderClass = URLClassLoader.class; 

  try { 
    Method method = classLoaderClass.getDeclaredMethod("addURL", new Class[]{URL.class}); 
    method.setAccessible(true); 
    method.invoke(systemClassLoader, new Object[]{url}); 
  } catch (Throwable t) { 
    t.printStackTrace(); 
    throw new IntrospectionException("Error when adding url to system ClassLoader "); 
  } 
}

This is easy and that can be done for any URLClassLoader. But of course, this is an ugly hack and that must not be always used but can be useful sometimes. An other way to do that is to create a new Class extending URLClassLoader and make the addUrl(URL url) public, but that can be done with the system ClassLoader.

Related articles

  • Develop a modular application - The loading
  • Java 7 : More dynamics
  • Java 7 : The new try-with-resources statement
  • JTheque : Problems when migrating to OSGi
  • Java 7 : Add "public defender methods" to Java interfaces
  • Tip : Profile an OSGi application with VisualVM
  • Comments

    Comments powered by Disqus