java Freemarker:if 语句中的枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12422105/
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
Freemarker: an enum in an if statement
提问by Geoffrey De Smet
In my if statement, I want to compare a variable, which is a JDK 1.5 enum, to an enum literal. For example:
在我的 if 语句中,我想将一个变量(JDK 1.5 枚举)与枚举文字进行比较。例如:
<#if type == ProblemStatisticType.BEST_SOLUTION_CHANGED>
...
</#if>
But I get this exception:
但我得到这个例外:
freemarker.core.InvalidReferenceException: Expression ProblemStatisticType is undefined on line 430, column 87 in index.html.ftl.
at freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:125)
at freemarker.core.TemplateObject.invalidTypeException(TemplateObject.java:135)
How can I do that?
我怎样才能做到这一点?
回答by ddekany
Unfortunately, the FreeMarker language doesn't have the concept of classes... but you can do this:
不幸的是,FreeMarker 语言没有类的概念......但你可以这样做:
<#if type.name() == "BEST_SOLUTION_CHANGED">
...
</#if>
Or if you trust the toString()
for the enum type, the .name()
part can be omitted.
或者,如果您信任toString()
枚举类型的 ,则.name()
可以省略该部分。
回答by michael
If you want to compare enums you should specify a constant enum value in double quotes like:
如果要比较枚举,应在双引号中指定常量枚举值,例如:
<#if type == "BEST_SOLUTION_CHANGED">
...
</#if>
回答by Jim Ford
I have used something like this successfully (in java 1.6 and 1.7, have not tried 1.5):
我已经成功地使用了这样的东西(在java 1.6和1.7中,没有尝试过1.5):
<#if type?? && statics["com.your.package.ContainingClass$TypeEnum"].BEST_SOLUTION_CHANGED.equals(type)>
Do some freemarker or HTML here
</#if>
This is with enum inside another class like:
这是在另一个类中使用枚举,例如:
class ContainingClass {
public enum TypeEnum {
WORST(0),
BEST_SOLUTION_CHANGED(1);
private int value;
private TypeEnum(int value) {
this.value = value;
}
public int value() {
return this.value;
}
};
}
And type variable is defined in java something like:
类型变量在java中定义如下:
TypeEnum type = TypeEnum.BEST_SOLUTION_CHANGED;