Is it possible to load / read / use a web jar without having to download it and use it in the classpath?
If so, how do I do this?
Is it possible to load / read / use a web jar without having to download it and use it in the classpath?
If so, how do I do this?
It is possible, but it is a complex and delicate task, not recommended for most cases, and it has several limitations.
Basically, you can load new classes manually, for example, through the loadClass
" of a ClassLoader
.
The problem is that within a Java Web application there is usually a hierarchy of ClassLoaders and how you will load classes depends on various factors and how they will be used.
You can use the more specialized class URLClassLoader
, which allows you to specify Jars and directories in the constructor, and the classes will be automatically located when you call the loadClass
or equivalent method.
Creating a new ClassLoader
allows you to isolate the loaded classes, which will not be able to access the normal classes of the system. This may or may not be desirable. One advantage of using a new ClassLoader
is that if it is no longer used and collected by the Garbage Collector , the loaded classes will be deleted too.
On the other hand, if you want to load classes as part of your program, you can try to use the current ClassLoader
of your web application. However, in this case, the class will no longer be unloaded from memory (at least in a regular JVM).
An alternative to this is to use the OSGi standard, where you can load and unload on-the-fly modules.
In short, giving more is complex and can lead to serious problems. It would be interesting to know exactly the purpose of doing this to determine if it is really necessary, the most appropriate method and if the effort is worth it.