简体   繁体   中英

java: load a specific version of a jar into my class

I have a situation where there are 2 versions of the same jar, say Jv1.jar and Jv2.jar. I have written a java class which requires all the classes in Jv2.jar. How do i got about it? Immediate help is highly appreciated. Thanks a ton.

The best solution would be to migrate all your code to use Jv2.jar and remove Jv1.jar.

Otherwise you must put Jv2.jar before Jv1.jar in the classpath, because the URLClassLoader will load the class from the first occurence. This solution is not recommended since it is not easy to understand for other developers or maybe yourself in a few weeks and depends on the implementation of URLClassLoader.

You must think of this as an jar overlay.

For example:

              Jv2.jar                                 Jv1.jar

    +- com                                    +- com
      +- company                                +- company
        +- A.class                               +- A.class
        +- B.class                               +- B.class
        +- C.class                               +- D.class           

Not assume that Jv2.jar is before Jv1.jar in the classpath.

  • If your code uses class A the Jv2.jar class A will be loaded.
  • If your code uses class D the Jv1.jar class D will be loaded.

Now here comes the tricky part:

If class D from Jv1.jar uses class B , class B of the Jv2.jar will be loaded and NOT class B from Jv1.jar.

So if D calls a method of B it can only work if class B is binary compatible between Jv1.jar and Jv2.jar.

But remember that it can still lead to unexpected behavior. Since binary compatibility does not necessarily mean that the method's pre and post conditions have not changed.

If you have the requirement that you need different versions of jars in the classpath and use the one or the other at the same time you should think about OSGI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM