关于android:为什么BuildConfig类使用Boolean.parseBoolean()而不是文字值?

Why does the BuildConfig class use Boolean.parseBoolean() instead of literal values?

当查看由Android Studio和Gradle插件生成的BuildConfig类时,可以看到BuildConfig.DEBUG字段是使用Boolean.parseBoolean(String)调用而不是使用布尔文字truefalse之一初始化的。

当我使用Gradle添加自定义构建属性时,我会像这样简单地做到这一点:

1
2
3
android {
    buildTypes.debug.buildConfigField 'boolean', 'SOME_SETTING', 'true'
}

但是查看生成的BuildConfig告诉我Google使用DEBUG标志采取了另一种方法:

1
2
3
4
5
6
7
8
public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");

  // more fields here

  // Fields from build type: debug
  public static final boolean SOME_SETTING = true;
}

使用Boolean.parseBoolean(String)代替文字有什么好处?


在代码中使用它们时,BuildConfig类中的布尔文字将产生IDE警告(至少在Android Studio中)。例如,在布尔表达式中使用它时,Android Studio将(错误地)建议简化布尔表达式,因为常量值始终是相同的(对于当前的构建变量而言)。

Android Studio producing code warning because of missing build configuration knowledge

该警告仅是因为Android Studio不知道BuildConfig.SOME_SETTING中的最终值对于其他构建版本可能有所不同。

为了保持代码的清洁和免于警告,您可以通过添加如下的IDE注释来告知Android Studio忽略此特定警告:

Add code comments to ignore IDE warnings

但这又会给代码增加一些噪音并降低可读性。通过使用Boolean.parseBoolean(String)方法初始化常量字段,您实际上在欺骗Android Studio,它将不再能够完全分析您的布尔表达式,因此不再产生警告。

Use parseBoolean(String) to prevent IDE warnings

这种方法非常有用,因为它可以使您的代码保持干净和可读性,而无需关闭重要的代码分析和警告生成。