Question

Are assertions always included into Android binary or do I need to specify -ea argument?

Can I deploy a final version of my app disabling assertions or is this system-dependent?

Was it helpful?

Solution

Java assertions can be en-/disabled at runtime, therefore the statements must be contained in the compiled code unless they are explicitly removed (and then, of course, they can't be enabled at runtime).

The documentation states that there is no direct support to actually strip the statements out at compile-time, though it mentions a trick you can use, which is basically a global "debug mode switch":

// causes the compiler to eliminate the statements
static final boolean asserts = false;

if (asserts) {
    assert <expr>; 
}

Personally I think that in this case you might just as well throw actual exceptions as it will be the same amount of overhead and because proper exception handling (especially in combination with unit test coverage) can be used for both development and production phase/code and doesn't require you to do extra work.

In any case, make sure that you only use the assert keyword for what it is intended for as it is easily misused. The above linked documentation article describes the correct usage quite well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top