Velocity Template is not detempletizing when a field inside object is accessed

1k views Asked by At

I've written the below code, which basically needs to print Hello simple Kishore by substituting the values of $string and $value.name inside the template Hello $string $value.name.

It substitutes the value of $string however $value.name is never replaced.
I tried to detempletize the value of $value and that works fine with TestClass$Sample@5594a1b5 as output, so the issue is with Template not being able to access the fields in the object.

Due to some constraints, I've to make use of VelocityEngine.evaluate itself and not VelocityEngine.mergeTemplate.

Code:

class Sample {
    private String name = "Kishore";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Test {
    public static void main(String args[]) throws Exception {
        String query = "Hello $string $value.name";

        VelocityContext vCtx = new VelocityContext();
        vCtx.put("string","simple");
        vCtx.put("value", new Sample());

        Writer out = new StringWriter();
        VelocityEngine engine = new VelocityEngine();
        engine.init();
        engine.evaluate(vCtx, out, "ERR:", new StringReader(query));

        System.out.println(out.toString());
    }
}

Output:

Hello simple $value.name
1

There are 1 answers

1
Maxim On BEST ANSWER

To fix this problem you should add public modifier for Sample class:

public class Sample {
    ...