根据风格排除代码段

Rot*_*ahu 1 android

我有一个具有多种风格的 Android 应用程序,并且我只希望特定风格包含特定的代码段。更具体地说,我想使用第三方库并仅以特定的方式添加该库的初始化代码。

public class MainApplication
    extends Application {

@Override
public void onCreate() {

    super.onCreate();

    //The library is only included in the build of specific flavors, so having this code in other flavors will not compile
    //I want the following code only to be included in the flavors that include the library
    SomeLibrary.init();

    //other code that is relevant for all flavors
    ...

}}
Run Code Online (Sandbox Code Playgroud)

Bar*_*ski 6

A)使用反射

defaultConfig {
    buildConfigField "boolean", "USE_THE_CRAZY_LIB", "false"
}
Run Code Online (Sandbox Code Playgroud)

productFlavors {
    crazyFlavor {
        buildConfigField "boolean", "USE_THE_CRAZY_LIB", "true"
        //... all the other things in this flavor
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的Application

public class MainApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        if (BuildConfig.USE_THE_CRAZY_LIB) {
            Method method = clazz.getMethod("init", SomeLibrary.class);
            Object o = method.invoke(null, args);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

B)使用同一类的两个不同版本来实现两种不同的口味

(有关该方法的更多信息,例如此处

  1. 对于其他口味(在src/otherFlavor/java):

    public class FlavorController {
        public static void init(){
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 适合您的口味(中src/crazyFlavor/java):

    public class FlavorController {
        public static void init(){
            SomeLibrary.init();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在你的Application

    public class MainApplication extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            FlavorController.init();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)