簡體   English   中英

使用引發異常的方法在靜態塊中初始化的最終靜態變量

[英]Final static variable initialized in static block using method that throws exception

考慮下面的代碼部分

private static class InnerClass
{
   private static final BufferedImage connectionImage; // line A
   private static final int width;
   // other not relevant fields
   static
   {
       try
       {
           connectionImage = ImageIo.read(...); // doeasn't really matter - any method that throws exception
       }
       catch(IOException e)
       {
           // handle
          connectionImage = null; // line B
       }
       if(connectionimage != null) // line C
       {
          width = connectionImage.getWidth();
       }
       else
       {
          width =0;
       }
   }
   // rest of the class definition
}

在這種情況下,我在行B上獲取了“可能已經分配了變量”的信息,如果在try{}塊中有更多行,並且在初始化變量后導致異常,則可能為true。 當我從A行中刪除final單詞時,它可以編譯,但是稍后當我嘗試使用connectionImage.getWidth()分配imageWidth / height(也是final static)時,我在static {}塊中收到警告(當然,如果它不為null) )。 警告是“初始化期間使用非最終變量”。 如果我決定在A行中使用final並刪除B行,那么我在C行上收到“變量connectionImage可能尚未初始化”的信息。

我的問題是:是否有一種方法可以使用引發異常的函數(或通常在try/catch內部)將static最終變量初始化並在static {}塊中使用,還是應該以其他方式處理? (構造函數)

注意(如果相關):是的,此類的名稱是為了告訴您它是內部類。 它也是靜態的,因為如果不是,我就不能在其中聲明靜態字段。

我知道如何編寫代碼來完成我不希望做的事情,但是由於我的方便,我想擁有這個內部類,並希望將某些行為分開。 我只是不知道靜態的最終靜態塊,嘗試/捕獲情況。 我在Google中找不到很好的解釋,我什至檢查了我以前的“ Thinkking in Java” ...

這是類似Java的東西-最終變量可以在靜態初始化塊中初始化嗎? 但是作者沒有嘗試在catch中初始化變量,也沒有在分配后在靜態塊中使用它們,因此以后不會收到“ Use of non-final ...”警告。

基本上,您應該使用局部變量:

BufferedImage localImage = null;
try
{
    localImage = ImageIo.read(...);
}
catch (IOException e)
{
    // No need to set a value, given that it's already going to be null.
    // You probably want to log though.
}
connectionImage = localImage;

現在您可以確定您的connectionImage變量將只分配一次。

然后,我將對width使用一個條件運算符,這樣可以更清楚地知道只有一個賦值:

width = connectionImage != null ? connectionImage.getWidth() : 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM