java 在 Android Studio 中使用 @NonNull 注释的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32652402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Right way to use the @NonNull annotation in Android Studio
提问by MMauro
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:
我想@NonNull
在 Android 中使用注释,但我想不出正确的方法。我建议你这个例子:
public void doStuff(@NonNull String s){
//do work with s...
}
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 thisquestion points out, they don't propagate very far. So I'd like to put a null check on my method, like this:
所以当我调用doStuff(null)
IDE 时会给我一个警告。问题是我不能依赖这个注释,因为就像这个问题指出的那样,它们不会传播很远。所以我想对我的方法进行空检查,如下所示:
if(s==null) throw new IllegalAgrumentException();
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.
但是,假设 IDEs!=null
会警告我这s==null
总是错误的。我想知道这样做的最佳方法是什么。
I personally think that there should be an annotation like @ShouldntBeNull
that onlychecks and warns that null isn't passed to it, but doesn'tcomplains when the value is null checked.
我个人认为应该有一个这样的注释@ShouldntBeNull
,它只检查并警告未将 null 传递给它,但在检查了 null 值时不会抱怨。
回答by TmTron
You can use Objects.requireNonNullfor that. It will do the check internally (so the IDE will not show a warning on your function) and raise a NullPointerExceptionwhen the parameter is null
:
您可以为此使用Objects.requireNonNull。它将在内部进行检查(因此 IDE 不会在您的函数上显示警告)并在参数为时引发NullPointerExceptionnull
:
public MyMethod(@NonNull Context pContext) {
Objects.requireNonNull(pContext);
...
}
If you want to throw another exception or use API level < 19, then you can just make your own helper-class to implement the same check. e.g.
如果您想抛出另一个异常或使用 API 级别 < 19,那么您可以创建自己的辅助类来实现相同的检查。例如
public class Check {
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new IllegalArgumentException();
return obj;
}
}
and use it like so:
并像这样使用它:
public MyMethod(@NonNull Context pContext) {
Check.requireNonNull(pContext);
...
}
回答by user60108
Google examplesdo it as follows
谷歌的例子如下
import static com.google.common.base.Preconditions.checkNotNull;
...
public void doStuff(@NonNull String sParm){
this.sParm= checkNotNull(s, "sParm cannot be null!");
}
回答by Darrell
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();
}
...
}
You'll need that //noinspection ConstantConditions
every time you do it.
//noinspection ConstantConditions
每次你都需要它。