简体   繁体   中英

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?

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.

In this case BuildConfig.SHORT_ENUM is a boolean .

Just use

if (BuildConfig.SHORT_ENUM){
  ...
}

In any case you can't do it in this way. It depends how you would like to use them. You have many options:

  • you can use 2 different classes in the different buildTypes.
  • just create a method which will return the values according to the condition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM