本文介绍了更好的办法调试只断言code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写我的第一个Android应用程序,我自由地使用断言()从junit.framework.Assert

I am writing my first Android application and I am liberally using asserts() from junit.framework.Assert

我想找到一种方法,以确保断言只编译到调试版本,而不是在发布版本。

I would like to find a way to ensure that the asserts are only compiled into the debug build, not in the release build.

我知道如何查询机器人:从清单调试的属性,所以我可以创建一个变量,并在下面fashon做到这一点:

I know how to query the android:debuggable attribute from the manifest so I could create a variable and accomplish this in the following fashon:

静态最终布尔mDebug = ...

static final boolean mDebug = ...

如果(mDebug)    Assert.assertNotNull(视图);

if (mDebug) Assert.assertNotNull(view);

有没有更好的方式来做到这一点?即我将preFER不要使用if(),每个断言。

Is there a better way to do this? i.e. I would prefer not to use an if() with each assert.

感谢

推荐答案

我认为Java语言的断言关键字可能是你想要的。在幕后,在断言关键字主要编译成Dalvik的字节code,做两件事情:

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:

  1. 检查是否静态变量 assertionsDisabled (在通过调用这个类的静态构造函数设置为 java.lang.Class.desiredAssertionStatus())是!= 0,如果是这样,什么也不做
  2. 如果它的的0,然后它再检查断言EX pression并抛出一个 java.lang.AssertionError 如果EX pression解析,有效地终止应用程序。
  1. 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
  2. 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.

在Dalvik运行在默认情况下已经断言关闭,因此 desiredAssertionStatus 总是返回1(或以上precisely,一些非零值)。这类似于在零售模式下运行。为了打开调试模式下,可以对模拟器或设备运行以下命令:

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).

但是请注意,上述的Dalvik code,检查 assertionsDisabled 的价值,并抛出一个的AssertionError 如果前pression是假的总是包含在字节$ C $的 C和宽松洒断言在你code可能导致字节$ C $ Ç膨胀。

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 asserts in your code may lead to byte code bloat.

请参阅本作更详细一点:Can我主张用在Android设备上?

Please see this for a bit more detail: Can I use assert on Android devices?

这篇关于更好的办法调试只断言code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 06:21