2013-05-16 124 views
0

有人知道是否有用於java的在線代碼分析器。我希望能夠檢查一些小部分的代碼。在線Java代碼分析器

例如:該方法具有這樣的警告:(空解引用)

private XMLGregorianCalendar asXMLGregorianCalendar(Date data) { 
      DatatypeFactory dateformat = null; 
      try { 
      dateformat = DatatypeFactory.newInstance(); 
      } catch (MyException e) { 
       /// 
      } 
      if (data == null) { 
      return null; 
      } else { 
      GregorianCalendar gregorianCal = new GregorianCalendar(); 
      gregorianCal.setTimeInMillis(data.getTime()); 
      return dateformat.newXMLGregorianCalendar(gregorianCal); 
    } 
} 

我的新版本是:

private XMLGregorianCalendar asXMLGregorianCalendar(Date data) throws ComponentBlockingException { 
     if (data == null) { 
      return null; 
     } 
     DatatypeFactory dateformat = null; 
     try { 
      dateformat = DatatypeFactory.newInstance(); 
     } catch (MyException e) { 
      //// 
     } 
     GregorianCalendar gregorianCal = new GregorianCalendar(); 
     gregorianCal.setTimeInMillis(data.getTime()); 
     return dateformat.newXMLGregorianCalendar(gregorianCal); 

    } 

} 

我認爲第二種方式應該沒問題。

+3

我不知道在線工具,但最新的IDE應該涵蓋這種類型的用例。 – assylias

+1

也許ide一個[ideone.com](http://ideone.com/)? – mleczey

+3

[FindBugs](http://findbugs.sourceforge.net/)不在線,但可以對這些事情有幫助,並且有一個體面的Eclipse插件。它還集成了Maven,Idea和NetBeans。 –

回答

4

我不確定任何可用的在線代碼anlayzer工具,但讓我試着幫助您進行代碼分析。

如果由於某種原因,以下try塊擊中異常

try { 
     dateformat = DatatypeFactory.newInstance(); 
    } 

那麼你的日期格式將保持爲空。所以以下聲明

return dateformat.newXMLGregorianCalendar(gregorianCal); 

很容易出現空指針異常。因此我相信你會得到靜態代碼anlayzer錯誤。

您必須確保dateformat在所有情況下初始化或非null,然後代碼到達您正在執行返回的行。

希望它有幫助!

+0

其他例外,比我抓住它,因爲如果它是MyException,一切都應該是確定的,因爲它永遠不會到達'返回' –

+0

沒有關鍵的是,如果發生異常,無論MyException或其他異常,然後dateformat將爲空。所以在這種情況下,沒有一點要求返回dateformat.newXMLGregorianCalendar(gregorianCal); 所以你應該拋出一個異常或者直接從方法中返回。 –

+0

@Juned,你正在做分析,而不是回答這個問題! –