如何在android中使用断言? [英] How to use assert in android?

查看:40
本文介绍了如何在android中使用断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Android 设备上使用 assert obj != null : "object cannot be null".断言似乎不起作用,所以我在网上搜索并找到了这个本地解决方案:

I want to use assert obj != null : "object cannot be null" on Android device. The assert doesn't seem to work, so I searched online and I found this local solution:

adb shell setprop debug.assert 1

adb shell setprop debug.assert 1

它可以在我的本地机器上运行.

it does work on my local machine.

我想使用我的 Eclipse 项目运行这个命令(所以它会在源代码管理中).我该怎么做?

I want to run this command using my Eclipse project(so it would be in the source control). How can I do it?

推荐答案

Assert 在 Android 中不起作用,因为大多数时候一个人不是在调试模式下运行,而是在一些优化的代码下运行.因此,正确的解决方案是手动抛出异常,代码如下:

Assert won't work in Android because most of the time a person isn't running in debug mode, but rather some optimized code. Thus, the proper solution is to manually throw an exception, with code like this:

if (obj==null) throw new AssertionError("Object cannot be null");

应该注意的是,在设计上,断言旨在用于调试代码,而不是用于发布时间代码.所以这可能不是抛出 Assert 的最佳用途.但这就是你仍然可以做到的方式,所以...

It should be noted that by design, Asserts are intended for debug code, and not for release time code. So this might not be the best use of throwing an Assert. But this is how you can do it still, so...

这篇关于如何在android中使用断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆