How to use an enum as a method parameter in Thymeleaf?

37 Views Asked by At

I am trying to invoke a method that takes an enum as a parameter from my Thymeleaf template. The enum is very straightforward:

public enum Language {
  C,
  JAVA,
  DOTNET
}

The method being invoked is equally simple:

public int count(Language l) {
  return counter.get(l);
}

And the call in the template is pretty vanilla too: entry.value refers to a DTO object that has the count(Language) method:

<td th:text="${entry.value.count(T(com.sample.Language).C)}" />

But when I try to load the template, I get this error: EL1004E: Method call: Method count(com.sample.Language) cannot be found on type com.sample.DTO. But if I provide a method in the DTO class that accepts a String and then converts it to the equivalent Language enum entry, all is good:

public int count(String lang) {
  return count(Language.valueOf(lang));
}

This seems contradictory. On the one hand, the error text says that Thymeleaf is looking for a method with a Language parameter, but then it actually invokes the method that has a String parameter. Is it possible to not need the String flavor of the count method in my DTO object?

1

There are 1 best solutions below

2
Ethan Conrad On

I commented on your question with a suggestion but have found a solution to your problem.

I read the documentation in https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html which states that:

"<span th:text="${book.author.name}">

The expression above is equivalent (both in OGNL and SpringEL) to:

((Book)context.getVariable("book")).getAuthor().getName()"

I then tried:

context.setVariable("entry", YourDTOClass)

Then using:

"${entry.count(@com.sample.Language@C)}"

obtained the correct result