method and classes available only for a flavour

436 Views Asked by At

Say I have flavour free / paid.

I want to call a method checkSubscription() for a paid feature. The classes referred inside that method will only be available for paid flavour, because I have put them in a different module, that compiles only for flavour paid.

Is above thing possible?, because when I'll run free flavour app, this should not give classNotFoundException. Please guide me.

Edit

Yes I am aware that I can check my flavour programmatically in Java like

if (BuildConfig.BUILD_VARIANT.equals("Your flavor name")){
   //do something
}

or by defining a buildConfigField.

I explain better

  • My class Example.java is in module PaidLibrary, and PaidLibrary is only compiled for the paid flavour.
  • Now I have a class ActivityExample.java, in which I have imported Example.class.
  • I check current flavour before using this Example.java, but will this create classNotFoundException because ActivityExample.java contains import and use of Example.java.
  • So this is my question that how to code for classes which are available for paid flavour?
2

There are 2 best solutions below

2
On

try using reflection:

ClassLoader classLoader = YOUR_CLASS.class.getClassLoader();
Class specificClass = classLoader.loadClass("YOUR_CLASS_RELATIVE_PATH");
Object result;  //This is object as your method can return any datatype

Method method = specificClass.getMethod(methodName, ARGS_TO_YOUR_METHOD_IF_ANY.class); // if your arg is a custom class 
result = method.invoke(specificClass.newInstance(), ARGS_TO_YOUR_METHOD_IF_ANY)
3
On

No, this is not possible, you have to provide Example.java or the activity that is using Example.java for both paid and free flavors of your app. When you generate build with free flavor, it will not be able resolve Example.java, leading to compile time error. You can just add a mock/dummy/placeholder Example.java for your free flavor to resolve build conflicts.