如何在 Android 调试版本中禁用断言

jbl*_*der 6 android android-gradle-plugin

在 Android Gradle 插件版本 4.1.0 中,它们发生了变化,因此断言现在总是在调试版本中抛出。如何禁用此功能?

调试版本中的断言

当您使用 Android Gradle 插件 4.1.0 及更高版本构建应用程序的调试版本时,内置编译器 (D8) 将重写应用程序的代码以在编译时启用断言,因此您始终使断言检查处于活动状态。

AGP 发行说明

Dus*_*tin 0

解决方法:

/**
 * Hack to work-around D8 change that always enables assertions in Android DEBUG builds.
 * Replace "assert boolean" with
 * "if (test) test(boolean)"
 *
 * In test case set "test = true"
 */
public class D8Hack {
    public static boolean test = false;

    public static void test(boolean b) {
        if (!b) {
            throw new RuntimeException("D8Hack.test() failed!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正在使用:

import static D8Hack.*;
public class SomeClass {
    public void main(String[] args) {
        int x = 1;
        //assert x==0
        if (test) test(x==0)
    }
}

public class SomeTest {
     static {
         D8Hack.test = true;
     }
     public void test() {
         SomeClass.main(null);
     }
}
Run Code Online (Sandbox Code Playgroud)

“断言”代码应该在调试中短路,R8 应该看到testAndroid 代码中始终为 false 并将其删除。希望他们能为我们这些在 Java 和 Android 之间共享代码的人添加一个标志。