javaandroidbuild.gradleandroid-buildandroid-buildconfig

BuildConfigField to decide how to define the member (enum)


build.gradle(Module):

productFlavors {
    mytest {
        ...
        buildConfigField "boolean", "SHORT_ENUM", "false"
    }
    mysecondtest {
        buildConfigField "boolean", "SHORT_ENUM", "true"
    }

In MyClass I want to define the enum member during the build according to the buildConfigField I've defined:

public class MyClass {
    // members initialization
    public enum MYENUM {
        if (BuildConfig.SHORT_ENUM) {
            FIRST(0),
            SECOND(1);
        }
        else { // SHORT_ENUM is false
            FIRST(0),
            SECOND(1),
            THIRD(2),
            FORTH(3);
        }
        private int value;
        MYENUM(int v) {
            value = v;
        }
    }
    ....
}

But it doesn't work. Is it possible to do what I would like to do? If yes, then how?


Solution

  • You can't just write if statements in a class definition.

    There is no ifdef and ifndef in Java.

    What you can do is create the java code folder for each of your product flavors, and then create the enum definition in each of those folders correctly.

    example:
    app/src/debug/java/my/package/MyEnum.java
    app/src/beta/java/my/package/MyEnum.java

    Then, when you build debug, it will use the debug version, and if you build beta, it will use the beta version.