java如何阻止编译器将单元化对象作为错误读取
我有eclipse,当我尝试查看一个未初始化的对象是否等于null时,它不允许我,它会出现一个“x可能未初始化”错误,我知道它应该可以工作
举例说明我的意思:
Object obj;
System.out.println(obj==null ? "no value":"has a value");
它不会编译,它会说“obj可能还没有初始化”,我如何在eclipse中更改编译器设置来解决这个问题
你可以在下面搜索框中键入要查询的问题!
我有eclipse,当我尝试查看一个未初始化的对象是否等于null时,它不允许我,它会出现一个“x可能未初始化”错误,我知道它应该可以工作
举例说明我的意思:
Object obj;
System.out.println(obj==null ? "no value":"has a value");
它不会编译,它会说“obj可能还没有初始化”,我如何在eclipse中更改编译器设置来解决这个问题
# 1 楼答案
编译器显示错误,因为规则是所有局部变量必须在首次读取之前初始化。因此,首先声明局部变量而不初始化它,稍后初始化它,然后使用它:
# 2 楼答案
解决方案是修复代码。此错误的目的是检测和防止错误。采取步骤让坏代码编译通常是一个非常糟糕的主意
# 3 楼答案
这是一个局部变量,您需要使用以下命令对其进行初始化:
虽然类、对象和数组的某些字段可能会隐式初始化为有用的默认值,但局部变量并非如此
如果您想理解这一点,那么
JLS7
的16.2.4
(Local variable declaration statements
)部分就是要阅读的部分,但需要一些时间才能理解,它相当迟钝:-)您可能希望从
16
(Definite Assignment
)部分的顶部开始,然后从那里开始工作。这篇文章的第一部分有两段,在这里最为贴切(我用斜体字强调):# 4 楼答案
不能。Java语言规范要求任何一致的Java编译器将其视为编译错误
没有Eclipse编译器设置导致它违反此规则
即使(假设)有这样的设置,我也认为当JVM试图加载字节码文件时,字节码文件的验证会失败。(如果您能以某种方式诱使JVM使用未初始化的局部变量的值,这将破坏运行时类型的安全性,导致JVM崩溃……甚至更糟。)
如果
obj
是一个实例变量而不是一个局部变量,那么它将默认初始化为null
,并且不会出现编译错误。但是局部变量不是默认初始化的# 5 楼答案
您不需要在eclipse中更改编译器设置来解决这个问题:只需初始化变量
obj
从Java Specification 4.12.5 - Initial Values of Variables开始:
如果你真的不想初始化
obj
,你需要让它成为一个类的成员而不是一个局部变量。然后它将有一个默认的初始值:(同样,参考Java Specification 4.12.5 - Initial Values of Variables)。。。但在引擎盖下,它仍在初始化