2012-07-22 57 views
8

我有以下代碼,將Java方法的結果分配給一個freemarker變量。如何從可能返回null的方法分配變量?

<#assign singleBenchmark = solverBenchmark.findSingleBenchmark(problemBenchmark)> 

問題是該Java方法的返回值可能是null。而且即使我檢查,如果該變量不null

<#if !singleBenchmark??> 
    <td></td> 
<#else> 
    <td>${singleBenchmark.score}</td> 
</#if> 

它仍然在<#assign ...>線崩潰,如果Java方法返回null,與此異常:

freemarker.core.InvalidReferenceException: Error on line 109, column 45 in index.html.ftl 
solverBenchmark.findSingleBenchmark(problemBenchmark) is undefined. 
It cannot be assigned to singleBenchmark 
    at freemarker.core.Assignment.accept(Assignment.java:111) 

我怎樣才能避免這種異常,而不必在我的ftl中多次調用findSingleBenchmark方法?

回答

10

正常的方式來處理不安全的API,如這與!(爆炸)操作:

<#assign singleBenchmark = solverBenchmark.findSingleBenchmark(problemBenchmark)!> 

這是this section of the FreeMarker docsthe reasoning is given here詳細。


如果你的代碼段是實際的代碼,你可能會縮短它(顯著)到:

<td>${singleBenchmark.score!""}</td>