VTL评估或定义对象引用

发布于 2024-09-26 22:21:26 字数 377 浏览 3 评论 0原文

我想创建一个宏,它将字符串作为参数并将其计算为对象。类似于:

#macro( valueTest $objRef)
  #define( $obj )#evaluate("$${objRef}")#end
  $obj.foo ## This would have to be translated to $obj.getFoo()
#end

不幸的是,$obj变量不指向可用于调用方法的对象引用。 $obj 是一个字符串,$obj.foo 不会尝试执行 getFoo。

不知怎的,我有一种感觉,这就是评估的本质,不可能做我想做的事。

我想做这样的事情的原因是因为我们有很少的宏将命令绑定路径和命令本身作为参数,我希望后者可以从第一个派生。

I would like to create a macro that takes a string as a parameter and evaluates that to an object. Something like:

#macro( valueTest $objRef)
  #define( $obj )#evaluate("${objRef}")#end
  $obj.foo ## This would have to be translated to $obj.getFoo()
#end

Unfortunately the $obj variable does not point to object reference that could be used to call methods. $obj is a String and $obj.foo does not try to execute getFoo.

Somewhy I have a feeling that this is the nature of evaluate and it is not possible to do what I want to.

the reason why I want to do smth like this is because we have quite few macros that take both command bind path and command itself as a parameter and I am hoping the latter could be derived from first.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沫尐诺 2024-10-03 22:21:26
Unfortunately, Velocity does not have a mechanism to define functions which return object references.  Macros are really intended to be a shortcut to display text.

在这种情况下,处理方法通常是用 Java 创建一个“工具”并将实例放入上下文中。工具只是一个普通的类,其方法可以返回您正在寻找的内容,

例如

使用“eval”方法创建一个对象,然后将其作为“referenceEvaluator”放入上下文中。

#set($obj = $referenceEvaluator.eval($objRef))

您可能会发现,如果避免双重求值并仅将一个对象插入到名为 $obj 的上下文中来执行您想要的操作,您的代码会更清晰。 (也有更好的性能)。

Unfortunately, Velocity does not have a mechanism to define functions which return object references.  Macros are really intended to be a shortcut to display text.

In cases like this, the way to proceed is generally to create a "tool" in Java and put an instance in the context. A tool is just an ordinary class with a method that returns what you are looking for

e.g.

create an object with an "eval" method, then put it in the context as "referenceEvaluator".

#set($obj = $referenceEvaluator.eval($objRef))

You might find that your code is clearer if you avoid the double evaluation and just insert an object into the context named $obj that does what you want. (better performance, too).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文