Java检查变量是否已初始化 [英] Java check to see if a variable has been initialized

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

问题描述

所以我对Java很新。在我的大学上课时,这个第一学期的重点是在使用名为ObjectDraw的java库时,将语法降低并掌握一些基本思想。下学期我们将开始远离ObjectDraw并进入核心Java。无论如何我遇到了一些问题,我需要使用类似于php的isset函数。我知道php和java非常不同,所以我不应该尝试比较它们,但php是我以前对类似编程的知识的唯一基础。我只是想知道是否有某种方法会返回一个布尔值,表示实例变量是否已初始化。例如......

So I'm pretty new to Java. Been taking a class at my college, this first semester is focussing on getting the syntax down and some of the basic ideas right while using a java library called ObjectDraw. Next semester we're going to start getting away from ObjectDraw and into core Java some more. Anyways I have run into a few problems where I need to use something similar to php's isset function. I know php and java are EXTREMELY different so I shouldn't try to compare them but php is my only basis of previous knowledge on something similar to programming. I just wondered if there was 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等。

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 with 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);

这篇关于Java检查变量是否已初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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