Search code examples
javavelocity

Velocity not finding method


I'm working on a webapp, using Apache Velocity as the template engine. I want it to show a HTML5 select, as shown below.

<select class="form-control" id="detailFunction">
    #foreach($function in $functions)
    <option id="$function.getId()">$function.getTitle()</option>
    #end
</select>

My Function class looks like this:

package com.stackoverflow;
class Function {
    private final int id;
    private final String title;

    Function(int id, String title) {
        this.id = id;
        this.title = title;
    }

    public int getId() {
        return this.id;
    }

    public String getTitle() {
        return this.title;
    }
}

$functions is a List<Function>. However, when I run this code, it says:

Object 'com.stackoverflow.Function' does not contain method getId() at /velocity/editor.vm[line 40, column 48]

while it's clearly there. Even changing $functions to the Function[] type does not change a thing. What could this be?


Solution

  • You forgot to add public access modifier to Function class so Velocity will be able to use it

    Velocity will only allow public methods on public classes to be called for security reasons.

    Declare your class:

     public class Function {
    

    It's not mandatory, but you probably should add your constructor also the public access if you will need it in velocity template

     public Function(int id, String title) {