I think the Java language's assert
keyword is likely what you want. Under the covers, the assert
keyword essentially compiles into Dalvik byte code that does two things:
- Checks whether the static variable
assertionsDisabled
(set in the class' static constructor via a call to java.lang.Class.desiredAssertionStatus()
) is != 0 and if so, does nothing
- If it is 0, then it checks the assertion expression and throws a
java.lang.AssertionError
if the expression resolves to false
, effectively terminating your application.
The Dalvik runtime by default has assertions turned off, and therefore desiredAssertionStatus
always returns 1 (or more precisely, some non-zero value). This is akin to running in "retail" mode. In order to turn on "debug" mode, you can run the following command against the emulator or the device:
adb shell setprop debug.assert 1
and this should do the trick (should work on the emulator or any rooted debugging-ready device).
Note however that the aforementioned Dalvik code that checks the value of assertionsDisabled
and throws an AssertionError
if the expression is false is always included in your byte code and liberal sprinkling of assert
s in your code may lead to byte code bloat.
Please see this for a bit more detail: Can I use assert on Android devices?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…