Search code examples
javahtmlfreemarker

Call function with dynamically generated name in Freemarker


Am I able to call a function from Java Object that has generated name from a few strings? In my example it's a simple getter. Just curious.

Process is a Java object like this:

public class Process {
   private int number = 0;

   public int getNumber() {
       return this.number;
   }

   public String getPropertyName() {
       return "number";
   }
}

Let's say we passed the Process object into freemarker template as a variable process with something like this:

return Results.html().render("process", new Process());

Now we have a html page containing the piece of code below. The method I have in mind should do something like this example (the example does NOT work!):

<#assign methodName = "process.get" + process.getPropertyName()?cap_first + "()">
<input name="${process.getPropertyName()}" type="number" value="${methodName}"/>

The result interpreted in html is this:

<input name="number" type="number" value="process.getNumber()"/>

But it's just a string and it's not interpreted in freemarker template as a value stored inside the method.

What do you think, is there a way to achieve this?


Solution

  • If you only want to dynamically access a field, then you can write it like that:

    <input name="${process.propertyName}" type="number" value="${process[process.propertyName]}"/>
    

    But if you really want to call method, then you can try with eval:

    <input name="${process.getPropertyName()}" type="number" value="${methodName?eval}"/>