Java 使用Thymeleaf键入强制转换EL表达式

Java 使用Thymeleaf键入强制转换EL表达式,java,type-conversion,el,type-erasure,thymeleaf,Java,Type Conversion,El,Type Erasure,Thymeleaf,如何在EL表达式中转换对象类型?Thymeleaf引擎似乎不理解以下内容: <span th:text="${((NewObjectType)obj).amount"></span> /** * Custom model for attributes displayed on the page. */ MyPageModel List<TableRows> tableRows; public List<TableRows&g

如何在EL表达式中转换对象类型?Thymeleaf引擎似乎不理解以下内容:

<span th:text="${((NewObjectType)obj).amount"></span>
/**
 * Custom model for attributes displayed on the page.
 */    
MyPageModel
    List<TableRows> tableRows;
    public List<TableRows> getTableRows(){...}
    ...
视图:


#
数量
1.
0

你能用你自己的模型包装这个列表吗?SpringMVC和Thymeleaf的部分价值主张是从视图层删除应用程序逻辑。转换是应用程序逻辑,应该在控制器内完成,或者如果必须…模型。因此,如果可能看起来像这样:

<span th:text="${((NewObjectType)obj).amount"></span>
/**
 * Custom model for attributes displayed on the page.
 */    
MyPageModel
    List<TableRows> tableRows;
    public List<TableRows> getTableRows(){...}
    ...
/**
*页面上显示的属性的自定义模型。
*/    
MyPageModel
列出表格行;
公共列表getTableRows(){…}
...
接下来,在controller方法中添加模型。下面是如何在模板中使用它将模型绑定到html表:

<table>
    <tr th:each="tableRow : ${model.tableRows}">
        <td class="date" th:text="${tableRow.amount}">$103</td>
    </tr>
    <tr th:unless="*{tableRow}">
        <td colspan="3">No amounts available</td>
    </tr>
</table>

$103
没有可用的金额

为什么必须键入cast obj?因为“obj”是从泛型列表中检索到的,类型擦除已删除其类型信息。我考虑了不同的类型擦除的可能性,并决定最好在客户端代码中将“obj”转换为其原始类型。谢谢。我也同意。但也许我应该这样问我的问题。如何将集合绑定到HTML表?因为现在我使用“th:each”循环一个集合,并在一行中显示每个项目。那是我需要转换类型的时候。用一个例子编辑了我的原始回复。谢谢跟进。谢谢。看,这几乎就是我所拥有的。问题出现在HTML代码的第二行(th:each)。tableRow的类型不是它应该的类型。例如,如果tableRow的类型是tableRow(具有“amount”属性),并且tableRow是从父类继承的,则在html代码中,tableRow在运行时的类型是ParentClass。因此,您将得到一个异常,指示“getAmount”不在“ParentClass”中。它不应该是ParentClass否,除非模型实现了接口或其他什么……不,我甚至不认为这是可能的。您的方法是类型化的(使用泛型)?如果模板中使用的模型表示该方法返回一个TableRow对象列表,那么thymeleaf应该得到一个TableRow…而不是TableRow正在扩展的任何对象。你能给我们看看你添加模型的控制器中的代码吗?更新了原始帖子。在运行时,类型擦除从字节码中删除T的类型信息,当从“get”方法返回时,类型为RootBase。
<table>
    <tr th:each="tableRow : ${model.tableRows}">
        <td class="date" th:text="${tableRow.amount}">$103</td>
    </tr>
    <tr th:unless="*{tableRow}">
        <td colspan="3">No amounts available</td>
    </tr>
</table>