使用 Java 5 枚举作为 Velocity 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1107884/
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
Using Java 5 enums as Velocity variables
提问by Maksym Govorischev
all. I need to use java 5 enum in velocity template, so that I could write something like
全部。我需要在速度模板中使用 java 5 枚举,以便我可以编写类似
public enum Level{
INFO, ERROR;
}
Velocity template:
#if($var == Level.INFO)
...
#else
...
#end
How can it be done? Thanks in advance.
怎么做到呢?提前致谢。
回答by Maksym Govorischev
Actually, instead of toString() method it would be better to use name(), as it returns exactly the value of enum and is final hence can't be overriden in future. So in velocity you can use something like
实际上,使用 name() 代替 toString() 方法会更好,因为它准确返回枚举的值并且是最终的,因此将来不能被覆盖。所以在速度中你可以使用类似的东西
#if($var.name() == "INFO")
回答by Will Glass
As of Velocity 1.5, if the two items being compared with == are of different classes, it automatically does a toString() on both. So try
从 Velocity 1.5 开始,如果与 == 比较的两个项目属于不同的类,它会自动对两者执行 toString() 。所以试试
#if($var == "INFO")
回答by Thilo
Not pretty, but one workaround would be to (manually) place the enum constants that you need into the Velocity context.
不漂亮,但一种解决方法是(手动)将您需要的枚举常量放入 Velocity 上下文中。
request.setAttribute('level_info', Level.INFO);
request.setAttribute('level_error', Level.ERROR);
Then you could say
那你可以说
#if ($var == $level_info)
Maybe easier: Just use the toString()of your enum instance
也许更简单:只需使用toString()您的枚举实例
#if ("$var" == 'INFO')

