Accessing constant values from an Apache Velocity

2019-04-19 03:31发布

Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?

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.

标签: java velocity
2条回答
戒情不戒烟
2楼-- · 2019-04-19 04:09

Velocity can only use anything it finds in its context, after e.g.

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.


Edit October 6 on 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.

查看更多
SAY GOODBYE
3楼-- · 2019-04-19 04:14

There are a number of ways.

1) You can put the values directly in the context.

2) You can use the FieldMethodizer to make all public static fields in a class available.

3) You can use a custom Uberspect implementation that includes public static fields in the lookup order.

4) You can use the FieldTool from VelocityTools.

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.

查看更多
登录 后发表回答