How do disable asserts in Android debug builds

Viewed 348

In Android Gradle Plugin version 4.1.0 they changed so assertions now always throw in debug builds. How to disable this feature?

Assertions in debug builds

When you build the debug version of your app using Android Gradle plugin 4.1.0 and higher, the built-in compiler (D8) will rewrite your app's code to enable assertions at compile time, so you always have assertion checks active.

AGP Release notes

1 Answers

Work-around:

/**
 * 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!");
        }
    }
}

In use:

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

The "assert" code should be short circuited in Debug and R8 should see that test is always false in the Android code and remove it. Hopefully they can add a flag for those of us who share code between Java and Android.

Related