Search code examples
freemarker

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


I iterate to a list of IColonne object. But I need to cast to the concret class to get specific attribut. My list have "Colonne" and "ColonneGroup" object.

The IColonne interface :

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

The Colonne concrete class:

public class Colonne implements IColonne {
    ....
}

The ColonneGroup concret class :

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

I need to access to access to the "texts" attribut. But I have "only" IColonne. So I need to cast to ColonneGroup. How can I do this?


Solution

  • I suppose you need to access texts from a FreeMarker template. As FTL is dynamically typed, you need no casting for that. You can just access the member, if the object has a public getTexts() method. Wether it has it (and that it's also non-null) you can test as colonne.texts??, or you can use the ! operator to give it a default. So it could be something like this:

    <#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>