2013-07-31 32 views
2

給出一個Java代碼,如:日食自動生成的實例= NULL遞歸調用

Something v = a.getB().getC().getD().getE(); 

有沒有在Eclipse(模板或外部插件)的方式來產生一個安全的鏈條電話爲:

if(a!=null && 
    a.getB()!=null && 
    a.getB().getC()!=null && 
    a.getB().getC().getD()!=null &&   
    a.getB().getC().getD().getE()!=null){ 
      Something v = a.getB().getC().getD().getE(); 
    }   
+0

這是有趣的東西:) – saurav

回答

1

你有沒有想過到try{} catch(NullPointerException e){}塊?它可能會覺得不那麼優雅,但如果任何方法調用失敗,它將停止您的代碼,因爲前一個返回null,並且如果它爲空,它將使您有機會給出默認值。

另一種辦法是這樣的:

Something v = /*Default Value*/ // Will be overwritten if subsequent methods succeed. 
Object temp = a.getB(); // Use whatever Object type getB() returns. 
if(temp != null){ 
    temp = temp.getC(); 
    /* If getC() returns a different type of object, 
    * either use a different variable or make the temp variable even broader 
    * (such as the generic Object type) */ 
    if(temp != null){ 
     temp = temp.getD(); 
     if(temp != null){ 
      temp = temp.getE(); 
      if(temp != null) 
       v = temp; 
       /* If all previous calls returned something substantial, 
       * v will be something useful */ 
      }//if(getE() != null) 
     }//if(getD() != null) 
    }//if(getC() != null) 
}//if(getB() != null) 

如果你願意,你可以使用一個稍微不那麼CPU高效,但更易於閱讀,版本的if語句不能嵌套。如果所有if語句都是在彼此之後執行的,則單個null將阻止所有下一個語句執行,儘管每次都會檢查它的值。

至於生成這些陳述,我不太確定。這將取決於您提前多久可以預測以前的方法調用返回的Object可用的新方法。如果你的目標是代碼自動生成,你可能會更好的我的第一個建議:try-catch

+0

是的,按照您的建議做相反的嘗試:儘管我不喜歡引發可能以其他方式控制的異常,但這樣做更容易。我完成了手動重構所有方法,因爲eclipse不提供這樣的重構可能性。 – JayZee

0

只有在沒有人會讀你的代碼時才這樣做。儘量避免生成的代碼,特別是您要求的代碼。

getB()方法被稱爲4個額外的時間等

通過檢查空手動您將學習編碼速度更快,使更少的錯誤不依賴於自動代碼校正;)

+0

謝謝fot的意見,但這不是一個答案。我需要重構300個無法防範null的方法,並在NullPointerExceptions上拋出噸。這就是爲什麼我越快越好,這就是爲什麼我要用自動化的方式來做到這一點。 – JayZee

+0

需要NullPointers。你確定自動重構你的代碼後,你的邏輯能夠工作嗎? – Tala

+0

是的,我有一個默認值分配給表達式。煩人的部分是防止呼叫路徑中發生的NPE。 – JayZee