Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to use different version of jar independently?  RSS feed

 
Matt Taylor
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a project that has uses an api. Inside the api it has a jar that contains httpclient version 4.2.3.

In my pom.xml, I also have httpclient but its is version 4.4 (latest version). My written code uses the httpclient (the reason why I imported it on my pom.xml).

However, how can I instruct during deploy time that use the httpclient 4.4 just on my written codes while use the 4.2.3 version on the api.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, unfortunately that is a problem in Java. You can't have two incompatible versions of the same library at the same time. If you put both HttpClient version 4.2.3 and version 4.4 in the classpath, then the JVM will just pickup the classes from the one that's first on the classpath. You can get all kinds of strange and hard to discover problems if you put two versions of the same library in the classpath.

The best thing you can do to fix this is change your own code so that it works with version 4.2.3, or find a new version of the API that currently needs 4.2.3 (find a version that can work with HttpClient 4.4).

This is due to the simplistic nature of Java's way to find classes: the classpath. The classpath is just a big list of directories and JAR files which is searched by the JVM to find classes, but there is no versioning mechanism at all.

There are ways to make it work, for example by using OSGi. OSGi is a module framework, that takes care of all the classloading and that does have a way to make it possible to let one module use version X of a library and another module use version Y of the same library. This is something that is, however, not trivial to apply to an existing project. It would mean you would have to change the whole structure of your project to make it suitable for OSGi.

Maybe Java's module system that is supposed to come with Java 9 in the future is going to make this easier.
 
Campbell Ritchie
Marshal
Posts: 55751
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Change the CLASSPATH with the -cp flag when you start the program? Presumably the two .jar files have different names.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!