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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:51:08  来源:igfitidea点击:

How to check if object is null or not except == null

javanull

提问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-80class 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 extendsame class BaseEntityso 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 truethen I ll call it's save method of repository to save data in DBotherwise 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:

请注意,标准库中有一个方法:

Objects.isNull(Object obj)

Objects.isNull(Object obj)

And another one which is the opposite of the above one:

另一个与上述相反的:

Objects.nonNull(Object obj)

Objects.nonNull(Object obj)

And there is yet another one which can be used to force a value to be not null, it throws a NullPointerExceptionotherwise:

还有另一个可以用来强制一个值 not nullNullPointerException否则它会抛出一个:

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。