How can I use two versions of the same library in the same project in Java?

11,143

You need to look into class loaders.

It's pretty tricky, but here's a good explanation for you.

Java, Classpath, Classloading => Multiple Versions of the same jar/project

You'll probably have to unload the old jar, load the new jar, run whatever the new function are, then unload that newer jar and reload the older jar.

Share:
11,143
Brian T Hannan
Author by

Brian T Hannan

Updated on June 18, 2022

Comments

  • Brian T Hannan
    Brian T Hannan almost 2 years

    Let's say I'm using xmlsec-1.5.8.jar for one part of my application (it has always used this).

    Then let's say I'm adding a new feature to my application and the new feature requires the use of xmlsec-2.0.5.jar.

    I don't want to replace xmlsec's usage for all the old code because I don't want to re-test all the code that has already been working (much of the code of which I don't know how it works because it was created before I arrived at this company).

    Is there a way in Java to use xmlsec-1.5.8.jar classes in one part of my project and then to use xmlsec-2.0.5.jar in another part?

  • Brian T Hannan
    Brian T Hannan over 8 years
    The problem with that is the processing is concurrent so either library could be called at any time by a process. If I unload it in process and another process goes to use it then it will throw a runtime class not found exception I believe. If this is the case, then this doesn't work.
  • Brian T Hannan
    Brian T Hannan over 8 years
    Plus, wouldn't it be slow to unload/load classes all the time while the application is running?
  • Bobby StJacques
    Bobby StJacques over 8 years
    You don't necessarily need to load or unload classes/libraries. You can create separate class loaders that load classes from different JAR files. The trick is in dispatching your jobs to the classes loaded by the correct loader. It can be done, and is in fact the mechanism that platforms like OSGi relies on (which dynamically loads and unloads services bundled as JAR files and makes their services available through shared interfaces at runtime).