相关疑难解决方法(0)

在构造函数中初始化静态final字段

public class A 
{    
    private static final int x;

    public A() 
    {
        x = 5;
    }
}
Run Code Online (Sandbox Code Playgroud)
  • final 表示变量只能分配一次(在构造函数中).
  • static 意味着它是一个类实例.

我不明白为什么这是禁止的.这些关键字在哪里相互干扰?

java static constructor final

80
推荐指数
4
解决办法
9万
查看次数

Java"空白最终字段可能尚未初始化"方法奇怪性抛出异常

我有一些代码:

final int var1;    

if ( isSomethingTrue ) {

   var1 = 123;

} else {
   throwErrorMethod();
}

int var2 = var1;
Run Code Online (Sandbox Code Playgroud)

而throwErrorMethod的定义如下:

private void throwErrorMethod() throws Exception{

   throw new Exception();

}
Run Code Online (Sandbox Code Playgroud)

我得到了声明的blank final field may not have been initialized编译错误var2 = var1.如果我内联方法,编译就好了!

  1. 编译器是否看到throws Exception调用的方法?
  2. 为什么有一个单词的错误may会停止编译?!?

java compiler-construction compiler-errors compiler-warnings

14
推荐指数
2
解决办法
2万
查看次数

最终字段可能尚未/已经初始化

可能重复:
如何处理抛出已检查异常的静态最终字段初始值设定项

在这个例子中,我得到了错误的空白最后一个字段myClass的可能被初始化:

private final static MyClass myClass; // <-- error

static {
    try {
        myClass = new MyClass(); // <-- throws exception
        myClass.init();
    } catch (Exception e) {
        // log
    }
}
Run Code Online (Sandbox Code Playgroud)

在那个例子中,我得到错误最终字段myClass可能已经被分配:

private final static MyClass myClass;

static {
    try {
        myClass = new MyClass(); // <-- throws exception
        myClass.init();
    } catch (Exception e) {
        myClass = null; // <-- error
        // log
    }
}
Run Code Online (Sandbox Code Playgroud)

那个问题有什么解决方案吗?

java final field initialization

10
推荐指数
2
解决办法
2万
查看次数