哪些条件会导致对象实例化返回 null?
下面的行是否有可能返回 null?
MyClass obj = new MyClass();
如果是这样,什么条件会导致返回值为 null?
Is it possible for the following line to return null?
MyClass obj = new MyClass();
If so, what conditions would cause a return value of null?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设虚拟机运行正常,
new
不可能返回 null。来自 Java 语言规范的第 15.9.4 节< /a>:
It's impossible for
new
to return null, assuming the VM is functioning correctly.From section 15.9.4 of the Java Language Specification:
不,这不能返回 null。但是,它可能会引发异常,并且根据您处理该异常的方式,处理异常后,
obj
引用可能仍然为空(如果您离开代码块,例如不捕获异常,obj
引用将不再存在,因此没关系)。构造函数中出现异常的原因是多方面的,例如,如果您耗尽内存(在这种情况下您会收到
OutOfMemoryError
),或者如果您访问仍为 null 的未初始化字段并会导致空指针异常
。No, this can't return null. It could, however, throw an exception and depending on how you handle that exception the
obj
reference might still be null after the exception is handled (if you leave the code block, e.g. by not catching the exception, theobj
reference would cease to exist and thus it wouldn't matter).Reasons for exceptions in a constructor are manifold, for example if you run out of memory (in which case you get an
OutOfMemoryError
) or if you access an uninitialized field which is still null and would cause aNullPointerException
.静态初始值设定项错误
,如
您无法在不指定上下文的情况下提出问题。在应用程序服务器中,上面的代码将创建 test=null 的 Myclass2。
为什么 ?因为错误通常是由应用程序服务器捕获的。
a static initializer error
like
You cannot ask your question without specifying the context. In an application server, the above will creare Myclass2 with test=null.
Why ? Because the Error is typically trapped by the application server.
简短的回答 - 不。
但您可以从构造函数抛出异常,在这种情况下,如果
obj
最初分配给null
,它将保持null
。Short answer - NO.
But you can throw an exception from a constructor, in which case, if
obj
was initially assigned tonull
, it will remainnull
.在我看来这是不可能的。如果不知何故你在 Java 中耗尽了内存,你会得到 <代码>OutOfMemoryError异常。
In my opinion it is impossible. If somehow you run out of memory in Java you will get
OutOfMemoryError
exception.