我写了下面的代码,基本上需要打印Hello simple Kishore
通过替换 $string
的值和 $value.name
在模板内部 Hello $string $value.name
.
它代替了$string
的值然而$value.name
永远不会被取代。
我试图去除 $value
的值这适用于 TestClass$Sample@5594a1b5
作为输出,所以问题在于模板无法访问对象中的字段。
由于某些限制,我必须使用 VelocityEngine.evaluate本身而不是 VelocityEngine.mergeTemplate .
代码:
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());
}
}
输出:
Hello simple $value.name
最佳答案
要解决此问题,您应该为 Sample
类添加 public
修饰符:
public class Sample {
...
关于java - 访问对象内部的字段时,Velocity 模板不会去模板化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41465888/