为什么BuildConfig类使用Boolean.parseBoolean()而不是文字值? [英] Why does the BuildConfig class use Boolean.parseBoolean() instead of literal values?
问题描述
查看由Android Studio和Gradle插件生成的BuildConfig
类时,可以看到BuildConfig.DEBUG
字段是使用Boolean.parseBoolean(String)
调用而不是使用布尔文字之一true
或
When looking at the BuildConfig
class generated by Android Studio and the Gradle plugin one can see that the BuildConfig.DEBUG
field is initialized using the Boolean.parseBoolean(String)
call instead of using one of the boolean literals true
or false
.
当我使用Gradle添加自定义构建属性时,我会像这样简单地做到这一点:
When I add custom build properties using Gradle I would simply do it like this:
android {
buildTypes.debug.buildConfigField 'boolean', 'SOME_SETTING', 'true'
}
但是查看生成的BuildConfig
告诉我Google使用DEBUG
标志采用了另一种方法:
But looking at the generated BuildConfig
tells me that Google has taken a different approach with the DEBUG
flag:
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)
代替文字有什么好处?
What is the benefit of using Boolean.parseBoolean(String)
instead of literals?
推荐答案
BuildConfig
类中的布尔文字将在您的代码中使用它们时产生IDE警告(至少在Android Studio中).例如,在布尔表达式中使用它时,Android Studio将(错误地)建议简化布尔表达式,因为常量值始终相同(对于当前的构建变量而言).
Boolean literals inside the BuildConfig
class are going to produce IDE warnings when using them in your code (at least within Android Studio). For example when using it in a boolean expression Android Studio will (mistakenly) recommend to simplify the boolean expression because the constant value is always the same (for current build variant that is).
此警告仅是因为Android Studio不知道BuildConfig.SOME_SETTING
中的最终值对于其他构建变体可能会有所不同.
This warning is only because Android Studio does not know that the final value inside BuildConfig.SOME_SETTING
may be different for other build variants.
要保持代码的清洁和免于警告,您可以通过添加如下所示的IDE注释来告诉Android Studio忽略此特定警告:
To keep the code clean and free of warnings you can tell Android Studio to ignore this specific warning by adding an IDE comment like this:
但是这又会给代码增加一些噪音并降低可读性.通过使用Boolean.parseBoolean(String)
方法初始化常量字段,您实际上在欺骗Android Studio,它将不再能够完全分析您的布尔表达式,从而不再产生警告.
But again this will add some noise to the code and reduce readability. By using the Boolean.parseBoolean(String)
method to initialize your constant field, you actually trick Android Studio which will no longer be able to completely analyze your boolean expressions, thus not generating warnings any longer.
这种方法非常有用,因为它可以使您的代码保持干净和可读性,而无需关闭重要的代码分析和警告生成.
This approach is very useful, as it keeps your code clean and readable, without turning off important code analysis and generation of warnings.
这篇关于为什么BuildConfig类使用Boolean.parseBoolean()而不是文字值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!