检查对象是否为null [英] checking if an object is null

查看:73
本文介绍了检查对象是否为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个简单的对象类作为testObj.java,带有getter和setter方法。

在我的代码中我需要检查testObj对象没有。


我的代码是:

testObj test = new testObj();

//调用方法A返回测试作为返回类型

if(test == null || test.equals(""))

{

系统。 out.println("测试对象为空);

}


但是我没有得到预期的结果。如何检查此测试对象是否为空?

解决方案

尝试使用.equals

展开 | 选择 | Wrap | 行号

暂时放在一边....


==比较一些东西(有人希望能够解释到底是什么)


.equals是一种由ALL对象提供的方法(你可以通过定义自己的equals方法来实现)。


那么,

如果你有一个名为myString的方法。


你可以定义equals来做任何事情(只要它t把一个对象作为输入并返回一个布尔值)


i有mopre说但是我忘了,所以如果你想要更多的信息或者这没有多大意义,请发布更多... 。





我有一个简单的对象类作为testObj.java,带有getter和setter方法。

在我的代码中,我需要检查testObj对象是否为空。


我的代码是:

testObj test = new testObj();

//调用方法A返回test作为返回类型

if(test == null || test.equals(""))

{

System.out.println("测试对象为空);

}


但我没有得到预期的结果。如何检查此测试对象是否为空?



当您使用new关键字获取对象并因此调用构造函数时,您将永远不会将该对象作为null。即构造函数永远不会返回null对象。


要测试对象是否为null,只需使用

展开 | 选择 | Wrap | 行号


Hi,
I''ve a simple object class as testObj.java with getter and setter methods.
In my code i need to check if the testObj object is null.

My code is :
testObj test = new testObj();
//invoke a method A which returns test as return type
if(test==null || test.equals(""))
{
System.out.println("The test object is null);
}

But i''m not getting the expected results. How to check if this test object is null?

解决方案

try using .equals

Expand|Select|Wrap|Line Numbers


As an aside in this vein....

== compares something (someone will hopefully explain exactly what)

.equals is a method provided by ALL objects (which you overide by defining your own equals methof).

So then,
if you have a method called myString.

You can define equals to do anything (as long as it takes an object as input and returns a boolean)

i had mopre to say but I forgot, so post more if you want more information or this doesn''t quite make sense....


Hi,
I''ve a simple object class as testObj.java with getter and setter methods.
In my code i need to check if the testObj object is null.

My code is :
testObj test = new testObj();
//invoke a method A which returns test as return type
if(test==null || test.equals(""))
{
System.out.println("The test object is null);
}

But i''m not getting the expected results. How to check if this test object is null?

When you get an object using the new keyword and thus calling the constructor, you will never get that object as null. i.e Constructors never return null objects.

To test if an object is null you simply use

Expand|Select|Wrap|Line Numbers


这篇关于检查对象是否为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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