有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何阻止编译器将单元化对象作为错误读取

我有eclipse,当我尝试查看一个未初始化的对象是否等于null时,它不允许我,它会出现一个“x可能未初始化”错误,我知道它应该可以工作

举例说明我的意思:

      Object obj;
      System.out.println(obj==null ? "no value":"has a value");

它不会编译,它会说“obj可能还没有初始化”,我如何在eclipse中更改编译器设置来解决这个问题


共 (5) 个答案

  1. # 1 楼答案

    编译器显示错误,因为规则是所有局部变量必须在首次读取之前初始化。因此,首先声明局部变量而不初始化它,稍后初始化它,然后使用它:

    Object obj = null;
    
     System.out.println(obj==null ? "no value":"has a value");
    
  2. # 2 楼答案

    How can I change my compiler settings in eclipse to fix this?

    解决方案是修复代码。此错误的目的是检测和防止错误。采取步骤让坏代码编译通常是一个非常糟糕的主意

  3. # 3 楼答案

    这是一个局部变量,您需要使用以下命令对其进行初始化:

    Object obj = null;
    

    虽然类、对象和数组的某些字段可能会隐式初始化为有用的默认值,但局部变量并非如此

    如果您想理解这一点,那么JLS716.2.4Local variable declaration statements)部分就是要阅读的部分,但需要一些时间才能理解,它相当迟钝:-)

    您可能希望从16Definite Assignment)部分的顶部开始,然后从那里开始工作。这篇文章的第一部分有两段,在这里最为贴切(我用斜体字强调):

    For every access of a local variable or blank final field X, X must be definitely assigned before the access, or a compile-time error occurs.

    Such an assignment is defined to occur if and only if either the simple name of the variable (or, for a field, its simple name qualified by this) occurs on the left hand side of an assignment operator.

  4. # 4 楼答案

    How can I change my compiler settings in eclipse to fix this?

    不能。Java语言规范要求任何一致的Java编译器将其视为编译错误

    没有Eclipse编译器设置导致它违反此规则

    即使(假设)有这样的设置,我也认为当JVM试图加载字节码文件时,字节码文件的验证会失败。(如果您能以某种方式诱使JVM使用未初始化的局部变量的值,这将破坏运行时类型的安全性,导致JVM崩溃……甚至更糟。)


    如果obj是一个实例变量而不是一个局部变量,那么它将默认初始化为null,并且不会出现编译错误。但是局部变量不是默认初始化的

  5. # 5 楼答案

    您不需要在eclipse中更改编译器设置来解决这个问题:只需初始化变量obj

          Object obj = null;
          System.out.println(obj==null ? "no value":"has a value");
    

    Java Specification 4.12.5 - Initial Values of Variables开始:

    A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16).

    如果你真的不想初始化obj,你需要让它成为一个类的成员而不是一个局部变量。然后它将有一个默认的初始值:(同样,参考Java Specification 4.12.5 - Initial Values of Variables

    public class Example {
    
        private static Object obj;
    
        public static void main(String[] argv) throws Exception {
            System.out.println(obj==null ? "no value":"has a value");
        }
    
    }
    

    。。。但在引擎盖下,它仍在初始化