Freemarker: an enum in an if statement
Solution 1
Unfortunately, the FreeMarker language doesn't have the concept of classes... but you can do this:
<#if type.name() == "BEST_SOLUTION_CHANGED">
...
</#if>
Or if you trust the toString()
for the enum type, the .name()
part can be omitted.
Solution 2
If you want to compare enums you should specify a constant enum value in double quotes like:
<#if type == "BEST_SOLUTION_CHANGED">
...
</#if>
Solution 3
I have used something like this successfully (in java 1.6 and 1.7, have not tried 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:
TypeEnum type = TypeEnum.BEST_SOLUTION_CHANGED;
Related videos on Youtube
Geoffrey De Smet
I am the lead of OptaPlanner, the open source constraint solver AI for Java (and Kotlin/Scala). It's used across the globe for the vehicle routing problem, employee rostering, maintenance scheduling, conference scheduling and other planning challenges. Twitter: @GeoffreyDeSmet
Updated on September 26, 2022Comments
-
Geoffrey De Smet almost 2 years
In my if statement, I want to compare a variable, which is a JDK 1.5 enum, to an enum literal. For example:
<#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?