如何在速度模板中获得动态 属性

How to get dynamic property in Velocity Template

我在使用 Velocity Template 编码时遇到了一个难题。

#set($key = "")

$key 是一个动态变量。

所以当我想获得另一个具有 属性 的变量的 属性 是 $key。我该怎么办?

#set($temp = #evaluate("$data.$key");

#set($temp = $data.$key);

全部无效。 请帮帮我!!!

要访问其他速度变量的 属性,您只需将其地址设为 $variableName.propertyName。参见 velocity properties。在你的情况下:

#set($temp = $data.key);

我不知道这种 built-in 反射能力,甚至 ClassTool 的速度工具支持反射但不允许执行:

It was not designed with reflective execution of code in mind and thus provides no facilities for code execution, nor direct access to the actual methods

由于传递的字符串是分两步计算的,因此您需要在第一步转义第一个美元(使用反斜杠)和引号(将它们加倍)。你会这样做:

#set($temp = "#evaluate(""$data.$key"")")

您可以使用 get():

#set( $temp = $data.get($key) )