2012-07-22 17 views
8

Ho il seguente codice in cui assegno il risultato di un metodo Java a una variabile freemarker.Come posso assegnare una variabile da un metodo che potrebbe restituire nulla?

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

Il problema è che il valore di ritorno di questo metodo Java potrebbe null. E anche se verifico se questa variabile non è null:

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

Si blocca ancora sulla linea <#assign ...> se questo metodo Java ritorna null, con questa eccezione:

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) 

Come posso evitare questa eccezione senza dover chiamare il metodo findSingleBenchmark più volte nel mio ftl?

risposta

10

Il modo normale per gestire API non sicuri come questo è con il ! (scoppio) esercente:

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

Questo è dettagliato in this section of the FreeMarker docs e the reasoning is given here.


Se il frammento di codice è il codice vero e proprio, si può accorciare esso (significativamente) a:

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