2

In my android project, I have to include a class file "X" from library "L". One dependency project also using the same Library "L" but older version.

Now my problem is when I include "X" it always imports latest version of "L". But in some areas I need to include older version. How to achieve this ?

Kamalakannan J
  • 2,818
  • 3
  • 23
  • 51
  • 1
    You should stabilize on one version of the library. Part of the whole point of build systems is to resolve dependencies and only import one of them when two things depend on the same library. – Karakuri Aug 23 '15 at 19:11
  • Your application cannot readily have two editions of the same Java class. Either everything needs to use the newer edition or everything needs to use the older edition. – CommonsWare Aug 23 '15 at 19:12

2 Answers2

3

You should not use the two different versions of same classes with same package structure in your project.

As ClassLoader will get confused which one to load.
Still if you really need to load two different versions of same class, refer this.

Community
  • 1
  • 1
Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
1

I agree with comments and answers. There must be only one version of a library, suggested approach is to use of latest one. Normally, libraries should support backward competibility (if no major release difference) with deprected annotation for warnings. If you add both, it's not guaranteed which version your classloader will pick.

As a very forcefull way to solve this is to manually implement a multi classloader approach.

Warning: This will work only if your relationship to this library is more like a service invocation based approach.

  1. Create another project which has dependencies to old jar user library and also old jar.
  2. Export all dependant jars to different folder.
  3. Within your application, manually create a new classloader and load all jars within that directory.
  4. When time comes switch to new classloader (overwrite current thread's classloader) then call required class create/call method operations by reflection. A wrapper class will be easier.
  5. After usage is done finally revert threads classloder then go on.

Note: Not sure, but probably default Java classloaders have parent&child relationship (OSGI classloders has it for sure). If so, you dont need to seperate common jars. When your parent project loads it, it should be accessible via child classloader as well. That's how you can pass a parameter object created by parent classloader to a object method loaded by child classloder.

hsnkhrmn
  • 961
  • 7
  • 20