Search code examples
javaandroidimportthreetenbpjava-time

How to easily switch imports sources in java?


NB: Please suggest a better title for this question.

Suppose I have two classes with the same name and I want to import one or the other before I compile depending on the use-case/app version. Is there a way to do it ?

Why do I need this ?, you may ask.

I need to use an important java library that uses java.time, but I also need to support min sdk 23 (Android 6.0). I could use threeThenABP in my Android app to be able to use all of the java.time APIs, but I need to import them from org.threeten.bp.

That important library is actually private. So, the idea is to make it use either java.time imports or org.threeten.bp imports in order to compile 2 versions that would be compatible with both Android and desktop Java applications.

I hope my explanations are clear enough. Thank you for your help.


Solution

  • I ended up using threetenbp in the library project, as suggested by @Ole V.V.
    Then, in my android project, I used threetenAbp (the android specific version) and I imported it the library using gradle. Finally, excluding the packages used in the library means that threetenAbp is used instead.

    implementation ('my-library') {
        exclude group: 'org.threeten'
    }
    

    NB: notice the difference (A) in threetenbp and threetenAbp.