简体   繁体   中英

Accessing constant values from an Apache Velocity template?

Is it possible to access a constant value (ie 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.

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.

Velocity can only use anything it finds in its context, after eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM