Java 如何检查对象是否为空,除了 == null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25642585/
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
How to check if object is null or not except == null
提问by user3145373 ツ
I want to make method that will check if the class instance is null or not.
我想创建一个方法来检查类实例是否为空。
Simply I know that i can use == null
, but I want to know that is there any other way that can be implemented to check if instance is null or not ?
只是我知道我可以使用== null
,但我想知道有没有其他方法可以实现来检查实例是否为空?
I have nearly 70-80
class instance. & all that class extend same Class BaseEntity
.
我几乎有70-80
类实例。& 所有该类都扩展了相同的 Class BaseEntity
。
at time of declaration I have declare each instance like :
在声明时,我已经声明了每个实例,例如:
Entity1 instance1 = null;
实体 1 实例 1 = 空;
like so I have defined all 70 class instances
.
像这样我已经定义了所有70 class instances
.
when they will be used I am initializing them using new.
but at end of my main Entity Processor
, I have to store data of each Entity id it is initialized, so for that I ll have to check if instance is null or not ?
何时使用它们我正在使用 new 初始化它们。但是在我的 main 结束时Entity Processor
,我必须存储它被初始化的每个实体 id 的数据,因此我必须检查实例是否为空?
All Entities extend
same class BaseEntity
so I have made following method.
All Entities extend
同一个班级,BaseEntity
所以我做了以下方法。
I know only one method :
我只知道一种方法:
public boolean checkIfEntityNull(BaseEntity entity){
return entity != null ? true : false;
}
if it returns true
then I ll call it's save method of repository to save data in DB
otherwise it ll not call save method.
如果它返回,true
那么我会调用它,save method of repository to save data in DB
否则它不会调用 save 方法。
So any guidance on it guys.
所以任何关于它的指导。
回答by icza
The easiest way to check is entity == null
. There is no shorter way to do that.
最简单的检查方法是entity == null
。没有更短的方法可以做到这一点。
Note that there is a method for this in the standard lib:
请注意,标准库中有一个方法:
And another one which is the opposite of the above one:
另一个与上述相反的:
And there is yet another one which can be used to force a value to be not null
, it throws a NullPointerException
otherwise:
还有另一个可以用来强制一个值 not null
,NullPointerException
否则它会抛出一个:
T Objects.requireNonNull(T obj);
T Objects.requireNonNull(T obj);
Note:The Objectsclass was added in Java 7, but the isNull()
and nonNull()
methods were added only in Java 8.
注:该对象在Java 7中添加类,但isNull()
与nonNull()
方法只在Java中添加8。