freemarker : 将 "Interface" 对象转换为真正的具体对象 class

freemarker : cast "Interface" Object to the real concret class

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

IColonne 界面:

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

科隆混凝土 class:

public class Colonne implements IColonne {
    ....
}

ColonneGroup 具体 class :

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

我需要访问 "texts" 属性。但是我有 "only" IColonne。所以我需要投射到 ColonneGroup。我该怎么做?

我想您需要从 FreeMarker 模板访问 texts。由于 FTL 是动态类型的,因此您不需要为此进行强制转换。如果对象具有 public 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>