Testing for instanceof

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Testing for instanceof

pfeigl
Is there a way to test in Thymeleaf whether an object is of a specific type?
Reply | Threaded
Open this post in threaded view
|

Re: Testing for instanceof

Zemi
Administrator
If you are in a hurry, you could use class name
    <p th:if="${someobject.class.name == 'java.lang.String'}">Someobject is a String</p>
but this is not a very robust approach.

You better use some utility class
    <p th:if="${typeChecker.isString(someobject)}">Someobject is a String</p>
where 'typeChecker' implementation is trivial:

    public class TypeChecker {
          public boolean isString(Object object) {
              return object instanceof String;
          }
    }
Reply | Threaded
Open this post in threaded view
|

Re: Testing for instanceof

pfeigl
Thanks, this helped and is probably best for native Thymeleaf.

However after some more reading I found the probably best (?) solution when using Spring.
SpEL supports two things:
1. instanceof as operator
2. T(name.of.class) notation to define a class in SpEL

So my final code looks like
<div th:if="${dataTable.data instanceof T(org.springframework.data.domain.Page)}"></div>