Are asserts available on Android?

前端 未结 3 661
天命终不由人
天命终不由人 2020-12-30 06:28

Are asserts available on Android? I have:

assert(null);

It does nothing and I am in the debug mode.

相关标签:
3条回答
  • 2020-12-30 06:35

    you can just use Android JUnit Assert:

    Assert.assertTrue(false);
    
    0 讨论(0)
  • Currently eclipse suggests the following:

    Assertions are unreliable. Use BuildConfig.DEBUG conditional checks instead.

    Issue Explanation:

    Assertions are not checked at runtime. There are ways to request that they be used by Dalvik (adb shell setprop debug.assert 1), but the property is ignored in many places and can not be relied upon. Instead, perform conditional checking inside if (BuildConfig.DEBUG) { } blocks. That constant is a static final boolean which is true in debug builds and false in release builds, and the Java compiler completely removes all code inside the if-body from the app.

    For example, you can replace

    assert speed > 0 
    

    with

    if (BuildConfig.DEBUG && !(speed > 0)) { throw new AssertionError(); }
    

    (Note: This lint check does not flag assertions purely asserting nullness or non-nullness; these are typically more intended for tools usage than runtime checks.)

    More Information: [Issue 65183: Intellij/Studio doesn't activate asserts when running Android code in debug mode]OK

    0 讨论(0)
  • 2020-12-30 06:54

    Yes, they are available.

    They are disabled in emulator by default. You will need to add -shell -prop debug.assert=1 command line parameters to Additional Emulator Command Line Options at the run configuration you're using to run your app.

    Assertions in eclipse

    The other thing you should be aware of is that your application installed on a device will not take into account assertions - they will be ignored.

    0 讨论(0)
提交回复
热议问题