Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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.

When I add custom build properties using Gradle I would simply do it like this:

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

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;
}

What is the benefit of using Boolean.parseBoolean(String) instead of literals?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 producing code warning because of missing build configuration knowledge

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.

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:

Add code comments to ignore IDE warnings

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.

Use parseBoolean(String) to prevent IDE warnings

This approach is very useful, as it keeps your code clean and readable, without turning off important code analysis and generation of warnings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...