简体   繁体   中英

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

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

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?

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM