使用Android Studio中的@NonNull标注正确的方式 [英] Right way to use the @NonNull annotation in Android Studio

查看:3059
本文介绍了使用Android Studio中的@NonNull标注正确的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 @NonNull 标注在Android中,但我想不出只是做了正确的方式。
我建议你​​这个例子:

I'd like to use the @NonNull annotation in Android, but I can't figure out just the right way to do it. I propose you this example:

public void doStuff(@NonNull String s){
     //do work with s...    
}

所以,当我打电话 doStuff(空)的IDE会给我一个警告。问题是,我不能依靠这个注解,因为像<一个href=\"http://stackoverflow.com/questions/13484202/use-nullable-and-nonnull-java-annotations-more-effectivly\">this问题指出,他们不很远传播。所以我喜欢把一个空检查我的方法是这样的:

So when i call doStuff(null) the IDE will give me a warning. The problem is that I cannot rely on this annotation since, like this question points out, they don't propagate very far. So I'd like to put a null check on my method, like this:

 if(s==null) throw new IllegalAgrumentException();

但IDE,假设取值!= NULL ,会警告我说,取值== NULL 始终假。我想知道什么是做到这一点的最好办法。

But the IDE, assuming that s!=null, will warn me that s==null is always false. I'd like to know what is the best way to do this.

我个人认为应该有像 @ShouldntBeNull 的注释,的检查,并警告说,空不传递给它,但的不会当值为null检查的抱怨。

I personally think that there should be an annotation like @ShouldntBeNull that only checks and warns that null isn't passed to it, but doesn't complains when the value is null checked.

推荐答案

您可以使用注释式燮pression禁用特定空检查的警告,例如:

You can use the comment-style suppression to disable that specific null check warning, e.g.:

    public MyMethod(@NonNull Context pContext) {
        //noinspection ConstantConditions
        if (pContext == null) {
            throw new IllegalArgumentException();
        }
        ...
    }

您将需要一个 // noinspection ConstantConditions 每次你做的时间。

You'll need that //noinspection ConstantConditions every time you do it.

这篇关于使用Android Studio中的@NonNull标注正确的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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