Reputation: 67
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?
Upvotes: 1
Views: 1183
Reputation: 10555
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.
Upvotes: 1
Reputation: 10295
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()]));
Upvotes: 2