SoFunction
Updated on 2025-03-10

Android uses reflection + try catch to implement the method of introducing dependency libraries on demand for SDK

During the Android development process of SDK, it is very likely that other three-party SDK libraries will be introduced within SDK. For example, the development process of SDK may include both Google and Facebook SDKs. But what should the accessor do if he only wants to access the SDK containing Google login? Can gradle only rely on Google's libraries and not rely on Facebook? This article is simple to useReflection + try catchIt can achieve on-demand access without the need to create a new module and consider the problem of code separation.

Do the following processing when using the three-party SDK in your own SDK code:

Original code:

Intent googleSignInIntent = (mLoginActivity, mSignInOption).getSignInIntent();
if (googleSignInIntent != null)
{
  (googleSignInIntent, requestCode);
}

Processed code:

try
{
  Class classGoogleSignIn = ("");
  Intent googleSignInIntent = (mLoginActivity, mSignInOption).getSignInIntent();
  if (googleSignInIntent != null)
  {
    (googleSignInIntent, requestCode);
  }
}
catch (Exception e)
{
  ();
}

That is, before using the three-party SDK code, add the code of class reflection, and then wrap it with try+catch. The parameters are the three-party SDK full class name (package name + class name)

Class classGoogleSignIn = ("xxx");

In this way, the accessor will just refer to the library they want to access. The unreferenced class will be received by the catch and will not crash. It is simple and convenient.

This is the article about Android using reflection + try catch to implement SDK to introduce dependency libraries on demand. For more related contents of Android implementing SDK to introduce dependency libraries on demand, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!