freemarker : cast “Interface” Object to the real concret class

早过忘川 提交于 2019-12-12 01:54:37

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/41099386/freemarker-cast-interface-object-to-the-real-concret-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!