1

Let's say I add the following dependency to my app level build.gradle file:

compile 'com.squareup.retrofit2:retrofit:2.3.0'

How can I check at runtime that a certain dependency exists or not?

Sneh Pandya
  • 8,197
  • 7
  • 35
  • 50
Fouad
  • 855
  • 1
  • 11
  • 30

2 Answers2

1

You would not be able to run the App in the first place, because if the dependency does not exist you can not build the .apk. There is no run-time checking for gradle dependencies.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • 1
    What i intend to do is check whether a certain library exists and change the logic accordingly. For example, if retrofit exists do something otherwise fallback to regular httpurlconnection – Fouad Oct 25 '17 at 13:21
  • @Fouad As I said that is not how dependencies are working. If it exist you can build the app else you can not. – Murat Karagöz Oct 25 '17 at 13:23
  • Nevermind, the answer provided by @Nanev is what i was looking for. I will mark his answer as correct answer to help others. – Fouad Oct 25 '17 at 13:24
  • @MuratKaragöz you seem to be missing the whole concept of compile classpath vs. runtime classpath. You can build your apk just fine, but you can be missing a dependency/library in your runtime classpath. Your apk will be built correctly, but it will fail at runtime if it ever tries to call the missing dependency – cesarmax Jul 29 '22 at 03:14
0

I was looking for the same and I couldn't find the answer. What I would do is the following:

A- if you do have the dependency at compilation time, then I would call any method from that library surrounded by try/catch:

try {
  Retrofit().whateverRetrofitApi()
  // if you get to this line it means the library is present    
} catch(e: Throwable) {
  // if you get to this line it means the library is not present
}

Probably some other exception/error like NoClassDefFoundError would be better to catch.

B- if you do not have the dependency at compilation time, and you do want to check if it's present at runtime, then you could perform the same thing, but using reflection instead.

Hope it helps

Zoe
  • 27,060
  • 21
  • 118
  • 148
cesarmax
  • 414
  • 1
  • 5
  • 12