为什么 BuildConfig class 使用 Boolean.parseBoolean() 而不是文字值?

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

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

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

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

但是查看生成的 BuildConfig 告诉我 Google 对 DEBUG 标志采取了不同的方法:

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) 而不是文字有什么好处?

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

此警告只是因为 Android Studio 不知道 BuildConfig.SOME_SETTING 中的最终值对于其他构建变体可能不同。

为了保持代码干净且没有警告,您可以告诉 Android Studio 通过添加 IDE 注释来忽略此特定警告,如下所示:

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

这种方法非常有用,因为它可以使您的代码保持整洁和可读,而不会关闭重要的代码分析和警告的生成。

在我看来,"trick"其实是很危险的,因为你不能根据BuildConfig.DEBUG进行条件编译!

if(!BuildConfig.DEBUG) { Log.d("Here we are verifying the signature!"); }

根据我的逆向工程,日志将保留在输出中。class 文件!

这对攻击者来说是一个很好的线索...