How to resolve jar conflicts in runtime?

16,481

Solution 1

You can create a package structure (same as the one in your conflicting jars) in your project folder with a different name & copy respective contents from any of the jars. Use one package from the jar and the other from your project (the new package which you just created) I have done this very recently and it worked.

Good Luck!

Solution 2

Your options in this case are.

1.(Best way) Modify app code to use latest version of jar. If your program depends on another pluggin which depends on the outdated jar file check for latest version of the pluggin.

  1. Use OSGi

  2. Use two classloaders. Need to study a little bit of theory and can sometimes lead to unexpected errors.

Now I am not going to put examples as there is plenty of info and examples in the links below to assist you

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

Jar hell: how to use a classloader to replace one jar library version with another at runtime

http://java.dzone.com/articles/java-classloader-handling

http://javarevisited.blogspot.in/2012/12/how-classloader-works-in-java.html

Solution 3

You can use different classloaders and run conflicting components in different sandboxes.

There is no way to dynamically pick which jar to use if both jars are on the classpath, and you are using the system classloading mechanism. Java classloading picks you the first class file.

Solution 4

Anything that is dynamically linked will have to have some way to distinguish what to link with at run time. That's the whole point of having package hierarchy, to compartmentalize the code. You can get around the issue of identical class names but once the packages are the same I don't know of a way to force the JVM to link against one over another.

Share:
16,481
Xianyi Ye
Author by

Xianyi Ye

Updated on June 04, 2022

Comments

  • Xianyi Ye
    Xianyi Ye almost 2 years

    I have two jars are conflicted. Both of them contain a class with the same package name and class name. Due to same reasons, I cannot remove either of them.

    So, is there any way to resolve this issue? Ideally, I hope there is a way can let me decide the class in which jars should be invoked during runtime.

    I do appreciate anyone's help.

  • Sanjeev Kumar Dangi
    Sanjeev Kumar Dangi over 6 years
    maven plugin maven.apache.org/plugins/maven-shade-plugin can do it for you.