Search code examples
javaclassloader

how to implement ClassLoader for a list of directories as classpath?


how to implement ClassLoader for a list of directories as classpath? e.g.,

public class MyClassLoader extends ClassLoader {

    private List<String> directories;

    ...
}

Search classes and resources under the directories.

Class.forName("mypackage.Foo", myClassLoader);
myClassLoader.getResourceAsStream("foo/bar.xml");

Any such classloader in java standard lib?


Solution

  • Yes, there is a standard classloader for this in Java called URLClassLoader:

    URL[] urls = {
        new URL("file:/path/to/dir1/"),
        new URL("file:/path/to/dir2/"),
        ...
    };
    
    ClassLoader loader = new URLClassLoader(urls);
    Class<?> foo = Class.forName("mypackage.Foo", true, loader);
    

    The only thing you will need to do is to convert a list of directories to an array of URLs. But I think this is easy. I leave it as an exercise :)