Java 检查变量是否已初始化

2022-01-18 00:00:00 initialization variables java

我需要使用类似于 php 的 isset 函数的东西.我知道 php 和 java 是非常不同的,但 php 是我以前对类似于编程的知识的唯一基础.是否有某种方法可以返回一个布尔值来判断实例变量是否已被初始化.比如……

I need to use something similar to php's isset function. I know php and java are EXTREMELY different but php is my only basis of previous knowledge on something similar to programming. Is there some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not. For example...

if(box.isset()) {
  box.removeFromCanvas();
}

到目前为止,当我的程序试图隐藏或删除尚未构造的对象时,我遇到了一个运行时错误.

So far I've had this problem where I am getting a run-time error when my program is trying to hide or remove an object that hasn't been constructed yet.

推荐答案

假设您对变量是否被显式赋值感兴趣,答案是不是真的".尚未显式分配根本的字段(实例变量或类变量)与已分配其默认值的字段(实例变量或类变量)之间绝对没有区别 - 0、false、null 等.

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

现在如果你知道一旦赋值,这个值就永远不会重新赋值为null,你可以使用:

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(这也避免了可能的 NullPointerException),但您需要注意值为 null 的字段"与未明确显示的字段"不同赋值".Null 是一个完全有效的变量值(当然对于非原始变量).实际上,您甚至可能想将上面的代码更改为:

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

局部变量也可以看到差异,在明确分配"之前无法读取它们 - 但可以明确分配的值之一是 null(对于引用类型变量):

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

相关文章