java 从 Apache Velocity 模板访问常量值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/148601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing constant values from an Apache Velocity template?
提问by Simon Nickerson
Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?
是否可以从 Velocity 模板访问常量值(即在 Java 类中定义的公共静态最终变量)?
I would like to be able to write something like this:
我希望能够写出这样的东西:
#if ($a lt Long.MAX_VALUE)
but this is apparently not the right syntax.
但这显然不是正确的语法。
采纳答案by Nathan Bubna
There are a number of ways.
有多种方法。
1) You can put the values directly in the context.
1)您可以将值直接放在上下文中。
2) You can use the FieldMethodizerto make all public static fields in a class available.
2) 您可以使用FieldMethodizer使类中的所有公共静态字段可用。
3) You can use a custom Uberspect implementation that includes public static fields in the lookup order.
3) 您可以使用自定义 Uberspect 实现,该实现在查找顺序中包含公共静态字段。
4) You can use the FieldToolfrom VelocityTools.
4) 您可以使用VelocityTools 中的FieldTool。
I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2.
我推荐 1 代表几个值,2 代表几个类,3 代表很多类和值,4 如果你已经在使用 VelocityTools 并且否则会使用 1 或 2。
回答by Angelo van der Sijpt
Velocity can only use anything it finds in its context, after e.g.
Velocity 只能使用它在其上下文中找到的任何东西,例如
context.put("MaxLong", Long.MAX_VALUE);
You cannot use statics, or access static members of things in Velocity's context due to the way its lookup works (see Velocity's Property lookup rules). The best thing to do is add the value you want to check against explicitly in your context.
由于查找的工作方式,您不能使用静态或访问 Velocity 上下文中事物的静态成员(请参阅 Velocity 的属性查找规则)。最好的做法是在上下文中明确添加要检查的值。
Edit October 6on second sight, it seems to be possible to access static members. See the velocity Developer guide - Support for "Static Classes"for more information. I have not tried this out, though.
编辑 10 月 6日第二眼,似乎可以访问静态成员。有关更多信息,请参阅velocity Developer guide - Support for“Static Classes”。不过,我还没有尝试过。

