0

I have two jars, the left.jar and the right.jar. They are similar but not identical.

left.jar:

package com.mydomain.config

public class PkgConfig {
    public static int getID() {
        throw new RuntimeException();
    }

    public static String getLeftValue() {
        throw new RuntimeException();
    }

    // the rest of the methods are the same with right.jar
}

right.jar:

package com.mydomain.config

public class PkgConfig {
    public static int getID() {
        throw new RuntimeException();
    }

    public static String getRightValue() {
        throw new RuntimeException();
    }

    // the rest of the methods are the same with left.jar
}

In my activity, I do this:

public void myMethod() {
    if(com.mydomain.config.PkgConfig.getID() > 1000) {
        mDeviceValue = com.mydomain.config.PkgConfig.getLeftValue();
    }
    else {
        mDeviceValue = com.mydomain.config.PkgConfig.getRightValue();
    }
}

And this is how I declared the dependency:

compileOnly files('libs/left.jar')
compileOnly files('libs/right.jar')

This setup gives me an error saying

error: cannot find symbol method getRightValue()

My goal is to create one APK out of this. I know I can use sourcesets and do this:

leftCompileOnly files('libs/left.jar')
rightCompileOnly files('libs/right.jar') 

but it creates two APKs. Is there a way to go around this problem?

user1506104
  • 6,554
  • 4
  • 71
  • 89
  • Have you checked this [SO Question](https://stackoverflow.com/questions/6879652/possible-to-use-two-java-classes-with-same-name-and-same-package)? Some answers suggest writing a custom class loader. – Abbas Jul 11 '19 at 08:42

1 Answers1

0

It is not possible to have two classes with the same fully-qualified name in the same APK. So, either:

  • Replace the two JARs with one JAR and one class, or

  • Rename one of the classes, or

  • Move one of the classes to a different package

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • By the way @CommonsWare, I am using compileOnly because the actual classes gets loaded on runtime by the specific device where the apk is loaded. I have Left device and Right device. left.jar is meant for Left device and right.jar is meant for Right device. Do you stand by your answer? – user1506104 Jul 13 '19 at 11:38
  • 1
    @user1506104: It *might* be possible for you to have a stub `PkgConfig` for compilation that has both the left and the right methods. That's basically how the `android.jar` files work. The hope is then, at runtime, ART (or Dalvik) will be able to match up the methods that exist in the real implementation, so long as you do not code to the methods that do not exist (e.g., try calling left on a right device). Obviously, this works for the Android SDK, but I don't know how much magic there might be in the build process that is specific to the Android SDK that would not work for your own code. – CommonsWare Jul 13 '19 at 11:46