Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I somehow include and use multiple versions of a given .jar library?

Tags:

java

android

I appreciate that this might sound absurd, but is it possible to drop two different versions of a .jar library into an Android project (where both versions obviously have identical or overlapping package and class names), and somehow explicitly point to one of them when importing the library's classes into my own Java sources?

My development environment is Android Studio with Gradle.

My reason for considering doing this (if it is possible) is because I rely on a closed-source vendor-supplied .jar driver library for a USB device that my Android application works with. The vendor has added support for newer chip versions in their latest driver, but at the same time they have dropped support for older chip versions. This is a decision they have made for their own good reason and it is unlikely to be reversed. An idea I have is to somehow carry both old and new versions of the library in my application so that I can continue to support the older hardware.

I suppose something like this would be theoretically possible, but a complicated affair, perhaps requiring one .jar to be decompiled and package names changed?

like image 697
Trevor Avatar asked May 07 '15 19:05

Trevor


People also ask

Can a class have multiple versions of the same method?

Yes, we can define multiple methods in a class with the same name but with different types of parameters.

Can a JAR file contain other JAR files?

A JAR file can contain anything you want, but the same limitation is there: the system class loader can't load classes that are in a JAR inside a JAR.

What is the difference between JAR and library?

A JAR serves the same function an an Assembly in the C#/. net world. It's a collection of java classes, a manifest, and optionally other resources, such as properties files. A library is a more abstract concept, in java, a library is usually packaged as a JAR (Java ARchive), or a collection of JARs.


1 Answers

To my amazement, I've very quickly had success at this using the jarjar utility as suggested by CommonsWare.

The key in understanding how to do this was this QA:

Hand Edit A Jar to Change Package Names

I renamed one of my .jars using the directions given above and I now have them both sat side by side in my project.

I don't want to duplicate SO content, but for completeness, I did the following:

Obtained the latest version of jarjar.

Created a configuration file called rules.txt containing a single line:

rule uk.co.dog.** uk.co.cat.@1

That's just an example. Given a .jar with the package uk.co.dog.*, the dog will change to cat. Obviously change this to suit your real case.

Then use the command line:

java -jar jarjar.jar process rules.txt in.jar out.jar

Where in.jar is the source .jar and out.jar is the transformed one.

like image 119
Trevor Avatar answered Oct 05 '22 23:10

Trevor