I know that I can use debugCompile
to only pull in a dependency
for the debug build
. Is there a good, streamlined way to do the
There is more cardinal method to connect stetho or any other lib only to debug builds - using reflection:
1) Connect your lib via debugImplementation - debugImplementation 'com.facebook.stetho:stetho:1.5.1'
2) Implement class with only static members - DynamicClassUtils:
public class DynamicClassUtils {
private static final String TAG = "DynamicClassUtils";
public static void safeInvokeStaticMethod(String fullClassName, String methodName, Class>[] types, Object... args) {
try {
Class> aClass = Class.forName(fullClassName);
Method aMethod = aClass.getMethod(methodName, types);
aMethod.invoke(null, args);
} catch (Throwable e) {
if (BuildConfig.DEBUG) {
Log.e(TAG, "Error when invoking static method, message: " + e.getMessage() + ", class: " + e.getClass());
e.printStackTrace();
}
}
}
public static T safeGetInstance(String fullClassName, Object... args) {
try {
ArrayList> formalParameters = new ArrayList<>();
for (Object arg : args) {
formalParameters.add(arg.getClass());
}
Class> aClass = Class.forName(fullClassName);
Constructor> ctor = aClass.getConstructor(formalParameters.toArray(new Class>[0]));
return (T) ctor.newInstance(args);
} catch (Throwable e) {
if (BuildConfig.DEBUG) {
Log.e(TAG, "Error when creating instance, message: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}
3) use that class to init stetho and its network interceptor:
if (BuildConfig.DEBUG) {
Class>[] argTypes = new Class>[1];
argTypes[0] = Context.class;
DynamicClassUtils.safeInvokeStaticMethod("com.facebook.stetho.Stetho", "initializeWithDefaults", argTypes, this);
}
if (BuildConfig.DEBUG) {
Interceptor interceptor = DynamicClassUtils.safeGetInstance("com.facebook.stetho.okhttp3.StethoInterceptor");
if (interceptor != null) client.addNetworkInterceptor(interceptor);
}