Comparing the enum constants in thymeleaf

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

I have an enum, Constants:

enum Constants {     ONE,TWO,THREE; }

How can I compare the enum Constants in Thymeleaf.

Thanks.

回答1:

To compare with an enum constant, use the following code:

th:if="${day == T(my.package.MyEnum).MONDAY}"


回答2:

One more way:

th:if="${constant.name() == 'ONE'}"

It's shorter but makes compare with string representation, can cause problem while refactoring.



回答3:

@Nick answer has a small syntax error, it's missing a final brace. It should be

th:if="${day == T(my.package.MyEnum).MONDAY}"


回答4:

th:if="${#strings.toString(someObject.constantEnumString) == 'ONE'}">


回答5:

Try this :

th:if="${ day.toString() == 'MONDAY'}"


回答6:

Another option is using the method name() of the enum in a switch. An example would be:

           

It is similar to a Java Switch swith ENUM instead of other answers like ${day == T(my.package.MyEnum).MONDAY} or ${#strings.toString(someObject.constantEnumString) == 'ONE'} which looks very strange.



回答7:

If you don't want to convert your Enum into a string in your object you can do it like this:

th:if="${#strings.defaultString(someObject.myConstant, 'DEFAULT_VALUE') == 'ONE'}"


回答8:

I prefere use wrapper around the enum.

public class ConstantsWrapper {     public static final instance = new ConstantsWrapper();     public Constants getONE() { return Constants.ONE }     public Constants getTWO() { return Constants.TWO }     public Constants getTHREE() { return Constants.THREE } } 

Next step is adding new instance of Wrapper into models

models.add("constantsWrapper", ConstantsWrapper.instance);

Now you have type safe access in thymeleaf template to the each value of Constants.

th:if="${value == constantsWrapper.getONE()}"

I know that this solutions needs to write more source code and create one instnace. Advantage is more type safe than call T() and write full qualified name directly into template. With this solution you can refactor without testing your templates.



回答9:

I tend to add isXXX() methods to my enums:

enum Constants {     ONE,TWO,THREE;     public boolean isOne() { return this == ONE; }     public boolean isTwo() { return this == TWO; }     public boolean isThree() { return this == THREE; } }

Then, if value is an instance of your enum, you can use th:if="${value.one}".



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!