2016-02-26 53 views
3

我正在嘗試爲最終圖像創建一個枚舉,其中變量'image'將從文件中加載。如果發生IOException,我想將'image'設置爲null。但是,根據編譯器的說法,當catch塊運行時,可能會或可能不會設置「image」。檢測構造函數中是否爲空白

public enum Tile { 
    GROUND("ground.png"), WALL("wall.png"); 
    final Image image; 
    Tile(String filename) { 
     try { 
      image = ImageIO.read(new File("assets/game/tiles/" + filename)); 
     } catch (IOException io) { 
      io.printStackTrace(); 
      image= null; // compiler error 'image may already have been assigned' 
     } 
    } 
} 

最終變量需要在構造函數中進行設置,因此,如果由於某種原因,圖像不能被讀取,它必須被設置的東西。但是,沒有辦法確定圖像是否已設置。 (在這種情況下,如果沒有設置圖像,捕獲塊纔會運行,但編譯器說它可能已經設置)

有沒有辦法讓我只能在catch塊中將圖像分配給null尚未設置?

回答

1

這裏是我結束了使用該解決方案。它添加了一個方法,以便在ImageIO類找到圖像時返回代碼,從而不會調用catch語句。

public enum Tile { 
    GROUND("ground.png"), WALL("wall.png"); 
    final Image image; 
    Tile(String filename) { 
     image = getImage(filename); 
    } 
    Image getImage(String filename) { 
     try { 
      return ImageIO.read(new File("assets/game/tiles/" + filename)); 
     } catch (IOException io) { 
      io.printStackTrace(); 
      return null; 
     } 
    } 
} 

但是,這不是真正的檢測空白最終變量的方法。我希望看看是否有辦法在try/catch中設置最終變量,而不用使用臨時變量來解決問題。

+0

這就是我會這樣做的。它重構代碼以突破加載圖像的邏輯,將值分配給實例字段。我會更進一步,將方法移出enum類並進入實用類(方法和代碼都不會與枚舉有關)。相比之下,在構造函數中使用臨時變量是一個糟糕的解決方案。 – Bohemian

4

嘗試使用本地臨時變量:

public enum Tile { 
    GROUND("ground.png"), WALL("wall.png"); 
    final Image image; 
    Tile(String filename) { 

     Image tempImage; 
     try { 
      tempImage= ImageIO.read(new File("assets/game/tiles/" + filename)); 
     } catch (IOException io) { 
      io.printStackTrace(); 
      tempImage= null; // compiler should be happy now. 
     } 

     image = tempImage; 
    } 
} 
+0

我想過使用臨時變量,但感覺應該有一個更清晰的方法來解決這個問題。 – XeroOl