如何在Java中创建未初始化的静态最终变量

Cal*_*000 5 java variables

下面的代码产生编译器错误Variable HEIGHT might not have been initialized(同样如此WIDTH).

我怎样才能声明一个未初始化的静态最终变量,就像我在下面尝试做的那样?

public static final int HEIGHT, WIDTH;
static{
    try {
        currentImage = new Image("res/images/asteroid_blue.png");
        WIDTH = currentImage.getWidth();
        HEIGHT = currentImage.getHeight();
    }catch (SlickException e){
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

swi*_*ler 3

  static {
    Image currentImage = null;
    try {
      currentImage = new Image("res/images/asteroid_blue.png");
    } catch (Exception e) {
      // catch exception - do other stuff
    } finally {
      if (currentImage != null) {
        WIDTH = currentImage.getWidth();
        HEIGHT = currentImage.getHeight();
      } else {
        // initialise default values
        WIDTH = 0;
        HEIGHT = 0;
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

无论发生什么(try/catch),您都必须为静态变量赋值 - 因此,应该使用finally。