【问题标题】:freemarker : cast "Interface" Object to the real concret classfreemarker:将“接口”对象转换为真正的具体类
【发布时间】:2016-12-12 11:02:15
【问题描述】:

我迭代到 IColonne 对象的列表。但是我需要转换为具体的类来获得特定的属性。我的列表有“Colonne”和“ColonneGroup”对象。

IColonne 界面:

public interface IColonne {
    String getFtlName();
    int getWidthPx(final int tableSize);
}

Colonne 具体类:

public class Colonne implements IColonne {
    ....
}

ColonneGroup 具体类:

public class ColonneGroup implements IColonne {
    private List<String> texts;
}

我需要访问“文本”属性。但我“只有” IColonne。所以我需要投到 ColonneGroup。我该怎么做?

【问题讨论】:

    标签: freemarker


    【解决方案1】:

    我想您需要从 FreeMarker 模板访问 texts。由于 FTL 是动态类型的,因此您不需要为此进行强制转换。如果对象具有公共 getTexts() 方法,您可以只访问该成员。不管它有它(并且它也是非空的),你可以测试为colonne.texts??,或者你可以使用! 操作符给它一个默认值。所以它可能是这样的:

    <#list colonnes as colonne>
      ...
      <#if colonne.texts??>
        Do something with colonne.texts
      </#if>
      ...
      <#!-- Or if you would #list the texts anyway: -->
      <#list colonne.texts!>
         <p>We have some texts here:
         <ul>
           <#items as text>
             <li>${text}</li>
           </#items>
         </ul>
      </#list>
      ...
    </#list>
    

    【讨论】:

    • 对不起,我的回答不是很清楚。但你的回答很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多