是否有办法检查变量是否在Java中定义?

时间:2022-10-27 01:54:57

In my app in android I need to check if a variable has been defined yet so I dont get a null pointer exception. Any way around this?

在我的android应用程序中,我需要检查变量是否已经定义,这样就不会出现空指针异常。解决这个问题的办法吗?

2 个解决方案

#1


24  

The code won't compile if you try to use an undefined variable, because, In Java, variables must be defined before they are used.

如果您试图使用未定义的变量,则代码不会编译,因为在Java中,必须在使用变量之前定义变量。

But note that variables can be null, and it is possible to check if one is null to avoid NullPointerException:

但是请注意,变量可以是null,可以检查一个变量是否为null,以避免NullPointerException:

if (var != null) {
    //...
}

#2


2  

if (variableName != null)
{
//Do something if the variable is declared.        
}
else
{
//Do something if the variable doesn't have a value        
}

I think that should do it.

我认为应该这样。

#1


24  

The code won't compile if you try to use an undefined variable, because, In Java, variables must be defined before they are used.

如果您试图使用未定义的变量,则代码不会编译,因为在Java中,必须在使用变量之前定义变量。

But note that variables can be null, and it is possible to check if one is null to avoid NullPointerException:

但是请注意,变量可以是null,可以检查一个变量是否为null,以避免NullPointerException:

if (var != null) {
    //...
}

#2


2  

if (variableName != null)
{
//Do something if the variable is declared.        
}
else
{
//Do something if the variable doesn't have a value        
}

I think that should do it.

我认为应该这样。