javaandroidjarmultiple-definition-error

Android Java - How to prevent multiple dex definitions?


Basically, my product is a jar file, and I expect my clients to decompress it and package the .class files in their jar files and then distribute their jar files to their application clients.

Therefore an application might end up using two different jar files that contain the same class definitions. Therefore the java compiler (or dex on android) will complain.

To illustrate a bit more:

  1. client1 takes my jar ==> decompress ==> package .class files in jar1
  2. client2 takes my jar ==> decompress ==> package .class files in jar2
  3. App takes jar1 and jar2 ==> problem! multiple definitions of the classes.

How do I prevent that?


Solution

  • There are a few approaches here:

    1) Don't do this! Usually dependencies are not repackaged in this way. Instead client1 would deliver their clients your jar (with version numbers) and your jar. Same for client2. Now if client3 is using client1 and client2 he can see if the versions they are expecting of your software match. If not, they are in trouble.

    2) Repackage the classes in your jar file for each client. That is when you give your jar to client1 put all the classes in com.my.package.client1 before you give it to them and have them work out of that package when accessing your jar. This means possibly duplicate code for client3 consuming client1 and client2 but multiple versions of your software can coexist.

    3) Have client1 and client2 use proguard to repackage all the classes from your jar before they distribute theirs. This is basically the same as answer 2 just automated by proguard to do the rewriting. This has the added benefit of making it harder for people to reverse engineer their (and your) code.