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

时间:2015-04-27 06:56:20

标签: android android-gradle buildconfig

查看Android Studio和Gradle插件生成的BuildConfig类时,可以看到使用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)代替文字有什么好处?

2 个答案:

答案 0 :(得分:20)

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

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

答案 1 :(得分:0)

在我看来,“技巧”实际上非常危险,因为您无法基于BuildConfig.DEBUG进行条件编译!

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

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

对于攻击者而言,这将是一个很好的线索...