简体   繁体   中英

URLClassLoader in java

I am working on a project which requires loading classes at Runtime, so I did some research and found out that I need to use Custom Class Loader. I implemented my own custom UrlClassloader and provided it with the url of my jar files, it worked correctly and the class files got loaded. I have read the java doc for URLClassLoader and they have mentioned clearly that any URL that ends with "/" is assumed to refer to a directory so does it mean that if I have multiple jar files in the directory my classloader will all load all of them, I tried it but it didn't work. so what's the logic behind that. please explain I am very much confused. what if I want multiple jars to be loaded at runtime from a directory?

You have to iterate over the files in the directory and add them one by one

List<URL> urls = new ArrayList<>();
try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(BASE_DIRECTORY), "*.jar")) {
    for (Path path : directoryStream) {
        urls.add(path.toUri().toURL());
    }
}

URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));

When it ends with "/", would be referring find loading content from that directory. Suppose you have an extracted package in that folder. If you have a class com.abc.Test , to load it form a folder, you would need the file com/abc/Test.class in the folder you are referring to.

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